1. 程式人生 > >安卓介面之Viewpager和Tablayout實現滑動介面

安卓介面之Viewpager和Tablayout實現滑動介面

摘要:六部實現選項卡介面

 

一.

在gradle檔案新增以下程式碼:

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

 在gradle檔案新增以上程式碼後,才能使用Tablayout(版本號28.0.0是我做實驗時最新的版本)

 

二.佈局程式碼

<android.support.design.widget.TabLayout

            android: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"/> <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分別為"行動","統計"選項卡介面

 

四.新建多個繼承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);