安卓界面之Viewpager和Tablayout实现滑动界面

君不见长松卧壑困风霜,时来屹立扶明堂。这篇文章主要讲述安卓界面之Viewpager和Tablayout实现滑动界面相关的知识,希望能为你提供帮助。
摘要:六部实现选项卡界面
 
一.
在gradle文件添加以下代码:

implementation \'com.android.support:design:28.0.0\'

  在gradle文件添加以上代码后,才能使用Tablayout(版本号28.0.0是我做实验时最新的版本)
 
二.布局代码
< android.support.design.widget.TabLayoutandroid:layout_width="match_parent" android:layout_height="wrap_content" app:tabMaxWidth="0dp" app:tabGravity="fill" app:tabMode="fixed" android:id="@+id/tablayout_id" android:textAlignment="center" app:tabSelectedTextColor="@color/tabindicatorcolor" app:tabTextColor="@color/tabtextcolor" app:tabIndicatorColor="@color/tabindicatorcolor" android:background="@color/colorPrimary"/>

< !--app:tabIndicatorColor :指示条的颜色-->
< !--app:tabIndicatorHeight :指示条的高度-->
< !--app:tabSelectedTextColor : tab被选中时的字体颜色-->
< !--app:tabTextColor : tab未被选中时的字体颜色-->


< android.support.v4.view.ViewPager android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/viewpager_id"> < /android.support.v4.view.ViewPager>

 
三.在res/layout目录下自定义xml文件作为fragment中的选项界面
action_fragment.xml和mark_fragment.xml分别为"行动","统计"选项卡界面
安卓界面之Viewpager和Tablayout实现滑动界面

文章图片

 
四.新建多个继承Fragment的子类返回选项界面
FragmentAction.java

public class FramentAction extends Fragment {public FramentAction() { }@Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.action_fragment,container,false); return view; } }

  FragmentMark.java
public class FragmentMark extends Fragment { public FragmentMark() { } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.mark_fragment,container,false); return view; }}

 
五.自定义继承FragmentPagerAdapter的子类ViewPagerAdater,重写getItem(),getCount(),getPageTitle()方法,添加AddFragment()方法
public class ViewPagerAdaper extends FragmentPagerAdapter {private final List< Fragment> fragmentList=new ArrayList< > (); private final List< String> fragementListTitle=new ArrayList< > (); public ViewPagerAdaper(FragmentManager fm) { super(fm); }@Override public Fragment getItem(int i) { return fragmentList.get(i); }@Override public int getCount() { return fragementListTitle.size(); }@Nullable @Override public CharSequence getPageTitle(int position) { return fragementListTitle.get(position); }public void AddFragemnt(Fragment fragment,String title){ fragmentList.add(fragment); fragementListTitle.add(title); } }

 
六.在MainActivity.java中实现以下代码:
tabLayout=findViewById(R.id.tablayout_id); viewPager=findViewById(R.id.viewpager_id); ViewPagerAdaper mAdaper=new ViewPagerAdaper(getSupportFragmentManager()); mAdaper.AddFragemnt(new FramentAction(),"行动"); mAdaper.AddFragemnt(new FragmentMark(),"统计"); viewPager.setAdapter(mAdaper); tabLayout.setupWithViewPager(viewPager);

【安卓界面之Viewpager和Tablayout实现滑动界面】 

    推荐阅读