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

本篇内容介绍了“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();
    }
}

“Android如何实现自动变换大小的组件ViewPager2”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注蜗牛博客网站,小编将为大家输出更多高质量的实用文章!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接