5.创建底部布局bottom_layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="match_parent"android:layout_height="55dp"android:background="@color/gray"><!--主页--><LinearLayoutandroid:id="@+id/id_tab_zy"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1"android:orientation="vertical"android:gravity="center"android:layout_gravity="center"><ImageViewandroid:id="@+id/tab_iv_zy"android:background="@drawable/zy_show"android:layout_width="32dp"android:layout_height="32dp"/><TextViewandroid:id="@+id/text_zy"android:layout_width="32dp"android:layout_height="wrap_content"android:text="主页"android:gravity="center"/></LinearLayout><LinearLayout> ... </LinearLayout><LinearLayout> ... </LinearLayout><LinearLayout> ... </LinearLayout>//除id、background、text属性不一致,其余三个LinearLayout内容和第一个LinearLayout一致,所以不重复展示</LinearLayout>
res目录
6.在MainActivity中创建initTabView()函数 实现View.OnClickListener函数并监听
private void initTabView() {llZy = findViewById(R.id.id_tab_zy);llZy.setOnClickListener(this);llTxl = findViewById(R.id.id_tab_txl);llTxl.setOnClickListener(this);llFx = findViewById(R.id.id_tab_fx);llFx.setOnClickListener(this);llMe = findViewById(R.id.id_tab_me);llMe.setOnClickListener(this);imZy = findViewById(R.id.tab_iv_zy);imTxl = findViewById(R.id.tab_iv_txl);imFx = findViewById(R.id.tab_iv_fx);imME = findViewById(R.id.tab_iv_me);imCurrent = imZy;}
@Overridepublic void onClick(View view) {changeTab(view.getId());}
private void changeTab(int position) {imCurrent.setSelected(false);switch (position){case R.id.id_tab_zy:viewPager.setCurrentItem(0);case 0:llZy.setSelected(true);imCurrent = imZy;break;case R.id.id_tab_txl:viewPager.setCurrentItem(1);case 1:llTxl.setSelected(true);imCurrent = imTxl;break;case R.id.id_tab_fx:viewPager.setCurrentItem(2);case 2:llFx.setSelected(true);imCurrent = imFx;break;case R.id.id_tab_me:viewPager.setCurrentItem(3);case 3:llMe.setSelected(true);imCurrent =imME;break;}}
7.将bottom_layout添加至activity_main中
<include layout="@layout/bottom_layout"/>
8.实现viewpager和底部的响应 在initViewPager()中添加
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {//可以添加滚动动画@Overridepublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {super.onPageScrolled(position, positionOffset, positionOffsetPixels);}@Overridepublic void onPageSelected(int position) {super.onPageSelected(position);changeTab(position);}@Overridepublic void onPageScrollStateChanged(int state) {super.onPageScrollStateChanged(state);}});
基本完成viewpager和frgement简单的联合应用