Android ViewPager2+Fragment+TabLayout的简单使用

【1】ViewPager的简单使用

来看个ViewPager的简单使用的例子(使用Androidx包下的ViewPager,不是ViewPager2)
看看主界面中的布局:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">


    <androidx.viewpager.widget.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:layout_margin="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.498" />


</androidx.constraintlayout.widget.ConstraintLayout>

再来上3个xml,用作填充ViewPager:
在这里插入图片描述

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="#FFF877">
</LinearLayout>

来看看适配器:

public class MyAdapter extends PagerAdapter {
    private List<View> views;

    public MyAdapter(List<View> views) {
        this.views = views;
    }

    @Override
    public int getCount() {
        return views.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        container.addView(views.get(position),0);
        return views.get(position);
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView(views.get(position));
    }
}

重写了里面的四个方法,这几个是必须的,要不然会报错
在这里插入图片描述

来看看主方法中:

public class MainActivity extends AppCompatActivity {
    private List<View> views = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewPager viewPager = findViewById(R.id.vp);
        LayoutInflater lf = getLayoutInflater().from(this);
        View view1 = lf.inflate(R.layout.view1,null);
        View view2 = lf.inflate(R.layout.view2,null);
        View view3 = lf.inflate(R.layout.view3,null);
        views.add(view1);
        views.add(view2);
        views.add(view3);
        viewPager.setAdapter(new MyAdapter(views));
    }
}

拿到ViewPager对象,然后将xml转换为View,传到适配器中,最后设置viewPager的适配器就行了。
运行效果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

【2】使用ViewPager2+Fragment+tabLayout

  • tabLayout 需要用到的工具:
    配合 TabLayout使用 所用到的相关辅助类
    implementation "com.google.android.material:material:1.1.0"
  • 下载(导入ViewPager2)

①创建几个Fragment,并配置好xml

我创建了三个,每个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"
    tools:context=".Blank1Fragment"
    android:background="#FFF111">
    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_gravity="center"
        android:src="@drawable/ic_android_black_24dp" />

</FrameLayout>

②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">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <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:id="@+id/vp2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp" />


</LinearLayout>

LinearLayout布局,加上TabLayoutViewPager2,再分别设置一下id

③创建adapter:

public class FragmentAdapter extends FragmentStateAdapter {
    public FragmentAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @NonNull
    @Override

    public Fragment createFragment(int position) {
        switch (position) {
            case 0:
                return new Blank1Fragment();
            case 1:
                return new Blank2Fragment();
            default:
                return new Blank3Fragment();
        }
    }

        @Override
        public int getItemCount() {
            return 3;
        }
}

createFragment方法是根据position来创建添加对应的FragmentViewPager2中去
getItemCount是获取Fragment的个数

④最后来看看MainActivity中的代码:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TabLayout tl = findViewById(R.id.tabLayout);
        ViewPager2 viewPager2 = findViewById(R.id.vp2);
        viewPager2.setAdapter(new FragmentAdapter(this));
        TabLayoutMediator tab = new TabLayoutMediator(tl, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                switch (position){
                    case 0:
                        tab.setText("Fragment1");
                        break;
                    case 1:
                        tab.setText("Fragment2");
                        break;
                    case 2:
                        tab.setText("Fragment3");
                        break;
                }
            }
        });
        tab.attach();
    }
}

先获取tabLayoutViewPager,然后设置ViewPager的适配器,最后利用TabLayoutMediatortabLayoutViewPager关联,TabLayoutMediator的前两个参数分别是tabLayoutviewPager,第三个是配置的方式,在这里可以设置标签的内容(甚至可以是图片+文字的格式),最后attach一下,引用以上配置。

⑤效果展示:

在这里插入图片描述

Android中,ViewPager2配合TabLayout以及Fragment一起使用,可以创建一个非常常见的滑动导航栏和片段切换界面。这是一个流行的组合,用于构建像新闻应用、图片画廊或设置菜单这样的用户界面。 1. **设置布局**: - 在XML布局文件中,添加一个`RecyclerView`作为View Pager,并将其id设为`view_pager`。 - 同时添加一个`TabLayout`,通常放置在顶部,用于显示各个选项卡,id例如设为`tab_layout`. 2. **初始化组件**: - 创建一个`TabLayoutMediator`实例,将TabLayoutViewPager关联起来,动态管理标签和视图之间的对应关系。 ```java TabLayoutMediator mediator = new TabLayoutMediator(tabLayout, viewPager, viewPager::setAdapter); mediator.attach(); ``` 3. **创建FragmentPagerAdapter**: - 自定义一个`FragmentPagerAdapter`,它可以管理多个`Fragment`实例。 ```java class MyFragmentAdapter extends FragmentStateAdapter { //... @NonNull @Override public Fragment createFragment(int position) { return MyFragment.newInstance(position); // "MyFragment"是你自定义的Fragment类 } } ``` 4. **设置Adapter**: - 将`FragmentPagerAdapter`设置到`ViewPager`上。 ```java viewPager.setAdapter(new MyFragmentAdapter(getSupportFragmentManager())); ``` 5. **处理Tab点击事件**: - TabLayout有内置的监听器,可以在选中新的标签时更新对应的Fragment。 ```java tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } //其他方法... }); ```
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值