Android实现自动变换大小的组件ViewPager2

ViewPager2的概念

ViewPager2是一个翻页视图组件

ViewPager2能做什么

  • 支持垂直方向的滑动且实现极其简单。
  • 完全支持RecyclerView的相关配置功能。
  • 支持多个PageTransformer。
  • 支持DiffUtil,局部数据刷新和Item动画。
  • 支持模拟用户滑动与禁止用户操作。

ViewPager2的用法

因为ViewPager2是基于RecyclerView的,所以在使用上与RecyclerView的使用基本一致

ViewPager2常用的API

 1. setAdapter()   为viewpager2设置是配置
 2. setOrientation()  设置视图翻页的方向,可以设置垂直方向,也可以设置水平方向。
 3. setPageTransformer() 设置翻页的动画

举个简单的例子,adapter部分的代码省略了

第一步: activity_main.xml

// 第一步: activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity"
 android:orientation="vertical">
 <TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Hello World!"
 app:layout_constraintBottom_toBottomOf="parent"
 app:layout_constraintEnd_toEndOf="parent"
 app:layout_constraintStart_toStartOf="parent"
 app:layout_constraintTop_toTopOf="parent" />
 <androidx.viewpager2.widget.ViewPager2
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:id="@+id/view_pager"/>
</LinearLayout>

第二步:创建适配器的视图

// 第二步:创建适配器的视图
<!-- ViewPager2要求每页的宽高都必须是match_parent -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">
 <ImageView
 android:id="@+id/iv_pic"
 android:layout_width="match_parent"
 android:layout_height="360dp"
 android:scaleType="fitCenter" />
 <TextView
 android:id="@+id/tv_desc"
 android:layout_width="match_parent"
 android:layout_height="wrap_content" />
</LinearLayout>

第三步: 创建适配器adapter

// 第三步:创建适配器adapter
public class viewpagerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
 // 声明一个上下文对象
 private Context mContext; 
 // 声明一个商品列表,用于渲染adapter
 private List<GoodsInfo> mGoodsList = new ArrayList<GoodsInfo>(); 
 // 函数构造
 public viewpagerAdapter(Context context, List<GoodsInfo> goodsList) {
 mContext = context;
 mGoodsList = goodsList;
 }
 // 创建列表项的视图持有者
 public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup vg, int viewType) {
 // 根据布局文件item_mobile.xml生成视图对象
 View v = LayoutInflater.from(mContext).inflate(R.layout.item_mobile, vg, false);
 return new ItemHolder(v);
 }
 // 绑定列表项的视图持有者
 public void onBindViewHolder(RecyclerView.ViewHolder vh, final int position) {
 ItemHolder holder = (ItemHolder) vh;
 holder.iv_pic.setImageResource(mGoodsList.get(position).pic);
 holder.tv_desc.setText(mGoodsList.get(position).desc);
 }
 // 定义列表项的视图持有者
 public class ItemHolder extends RecyclerView.ViewHolder {
 public ImageView iv_pic; // 声明列表项图标的图像视图
 public TextView tv_desc; // 声明列表项描述的文本视图
 public ItemHolder(View v) {
 super(v);
 iv_pic = v.findViewById(R.id.iv_pic);
 tv_desc = v.findViewById(R.id.tv_desc);
 }
 }
}

第四步:书写MainAcvitivity.java,调用ViewPager的API

//第四步:书写MainAcvitivity.java,调用ViewPager的API
public class MainActivity extends AppCompatActivity {
 private List<GoodsInfo> viewPagerList = new ArrayList<>();
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 initData();
 // 从布局文件中获取翻页视图
 ViewPager2 viewPager2 = findViewById(R.id.view_pager);
 // 构建适配器
 viewpagerAdapter vpa = new viewpagerAdapter(viewPagerList);
 // 设置翻页视图的排列方向为水平方向
 viewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
 // 为翻页视图添加适配器
 viewPager2.setAdapter(vpa);
 }
 private void initData(){
 GoodsInfo g1 = new GoodsInfo("123", R.drawable.cloudy);
 viewPagerList.add(g1);
 GoodsInfo g2 = new GoodsInfo("456", R.drawable.moon);
 viewPagerList.add(g2);
 GoodsInfo g3 = new GoodsInfo("789", R.drawable.sunny);
 viewPagerList.add(g3);
 }
}

有没有发现,这个和recycleView的写法一摸一样。

ViewPager2与fragment结合使用

第一步:activity_main.xml视图

// 第一步:activity_main.xml视图 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity"
 android:orientation="vertical">
 <TextView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Hello World!"
 app:layout_constraintBottom_toBottomOf="parent"
 app:layout_constraintEnd_toEndOf="parent"
 app:layout_constraintStart_toStartOf="parent"
 app:layout_constraintTop_toTopOf="parent" />
 <androidx.viewpager2.widget.ViewPager2
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:id="@+id/view_pager"/>
</LinearLayout>

第二步:创建fragment所需要的视图fragment_blank.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@color/white"
 tools:context=".BlankFragment">
 <!-- TODO: Update blank fragment layout -->
 <TextView
 android:id="@+id/mTextView"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:text="@string/hello_blank_fragment"
 android:textSize="36sp"
 android:gravity="center"/>
</FrameLayout>

第三步:fragment所需的代码

public class BlankFragment extends Fragment {
 private static final String ARG_PARAM1 = "param1";
 String mTextString = "xxx";
 View rootView;
 public static BlankFragment newInstance(String param1) {
 BlankFragment fragment = new BlankFragment();
 Bundle args = new Bundle();
 args.putString(ARG_PARAM1, param1);
 fragment.setArguments(args);
 return fragment;
 }
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 if (getArguments() != null) {
 mTextString = getArguments().getString(ARG_PARAM1);
 }
 }
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
 Bundle savedInstanceState) {
 if(rootView == null) {
 rootView = inflater.inflate(R.layout.fragment_blank, container, false);
 }
 initView();
 return rootView;
 }
 private void initView() {
 TextView textView = rootView.findViewById(R.id.mTextView);
 textView.setText(mTextString);
 }
}

第四步:创建承载fragment所需要的适配器

public class MyFragmentAdapter extends FragmentStateAdapter {
 List<Fragment> fragments = new ArrayList<>();
 public MyFragmentAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle, List<Fragment> fragments) {
 super(fragmentManager, lifecycle);
 this.fragments = fragments;
 }
 @NonNull
 @Override
 public Fragment createFragment(int position) {
 return fragments.get(position);
 }
 @Override
 public int getItemCount() {
 return fragments.size();
 }
}

第五步:书写MainAcvitivity.java,调用ViewPager的API

public class MainActivity extends AppCompatActivity {
 ViewPager2 viewPager2;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 initPage();
 }
 private void initPage() {
 List<Fragment> fragments = new ArrayList<>();
 fragments.add(BlankFragment.newInstance("fragment1"));
 fragments.add(BlankFragment.newInstance("fragment2"));
 fragments.add(BlankFragment.newInstance("fragment3"));
 fragments.add(BlankFragment.newInstance("fragment4"));
 viewPager2 = findViewById(R.id.myViewPager);
 viewPager2.setAdapter(new MyFragmentAdapter(getSupportFragmentManager(),
 getLifecycle(),fragments));
 }
}

ViewPager2与导航栏配合使用

代码简写,只写相关的部分

// activity_main.xml 写上用到的两个组件TabLayout与ViewPager2
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".MainActivity">
 <com.google.android.material.tabs.TabLayout
 android:id="@+id/mTabLayout"
 android:layout_width="match_parent"
 android:layout_height="0dp"
 android:layout_weight="0.1">
 <com.google.android.material.tabs.TabItem
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Monday" />
 <com.google.android.material.tabs.TabItem
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Tuesday" />
 <com.google.android.material.tabs.TabItem
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Wednesday" />
 </com.google.android.material.tabs.TabLayout>
 <androidx.viewpager2.widget.ViewPager2
 android:layout_width="match_parent"
 android:layout_height="0dp"
 android:layout_weight="1"
 android:id="@+id/myViewPager"
 android:background="@color/purple_500"
 >
 </androidx.viewpager2.widget.ViewPager2>
</LinearLayout>
public class MainActivity extends AppCompatActivity {
 ViewPager2 viewPager2;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 initPage();
 }
 private void initPage() {
 List<Fragment> fragments = new ArrayList<>();
 fragments.add(BlankFragment.newInstance("fragment1"));
 fragments.add(BlankFragment.newInstance("fragment2"));
 fragments.add(BlankFragment.newInstance("fragment3"));
 fragments.add(BlankFragment.newInstance("fragment4"));
 viewPager2 = findViewById(R.id.myViewPager);
 viewPager2.setAdapter(new MyFragmentAdapter(getSupportFragmentManager(),
 getLifecycle(),fragments));
	//绑定使用
	new TabLayoutMediator(findViewById(R.id.mTabLayout),viewPager2,new TabLayoutMediator.TabConfigurationStrategy(){
 @Override
 public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
 switch (position){
 case 0:
 tab.setText("1");
 break;
 case 1:
 tab.setText("2");
 break;
 case 2:
 tab.setText("3");
 break;
 }
 }
 }).attach();
 }
}
作者:Dormiveglia-flx原文地址:https://feilx.blog.csdn.net/article/details/129539274

%s 个评论

要回复文章请先登录注册