Fragment + ViewPager +TabLayout

独自空忆成欢 提交于 2019-12-04 18:27:30

1.添加依赖

com.android.support:design:25.3.1

 

2.XML布局文件

    <android.support.design.widget.TabLayout
        android:id="@+id/TabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ></android.support.design.widget.TabLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/ViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/TabLayout"></android.support.v4.view.ViewPager>

 

3.代码实现

public class MainActivity extends AppCompatActivity {

private TabLayout mTabLayout;
    private ArrayList<Fragment> mList = new ArrayList<>();
    private AFragment aFragment;
    private BFragment bFragment;
    private CFragment cFragment;
    private ViewPager mViewPager;
    private MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView(){

        mTabLayout = (TabLayout) findViewById(R.id.TabLayout);
        mViewPager = (ViewPager) findViewById(R.id.ViewPager);
        aFragment = new AFragment();
        bFragment = new BFragment();
        cFragment = new CFragment();
        mList.add(aFragment);
        mList.add(bFragment);
        mList.add(cFragment);
        myAdapter = new MyAdapter(getSupportFragmentManager(),mList);
        mViewPager.setAdapter(myAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        mTabLayout.getTabAt(0).setText("电影");
        mTabLayout.getTabAt(1).setText("音乐");
        mTabLayout.getTabAt(2).setText("阅读");


    }
}

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!