TabLayout的简单例子


XML中配置:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
   
    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <--在TabLayout中也可以设置颜色
       app:tabIndicatorColor="@color/white"  //Tab下划线的颜色
       app:tabSelectedTextColor="@color/gray"  //Tab文字被选中后的颜色
       app:tabTextColor="@color/white"     //Tab文字的默认颜色
     -->

</LinearLayout>



Adapter:

public class FragmentAdapter extends FragmentStatePagerAdapter {
    private List<Fragment> mFragments;
    private List<String> mTitles;

    public FragmentAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titles) {
        super(fm);
        mFragments = fragments;
        mTitles = titles;
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles.get(position);
    }
}

Activity:

public class DemoActivity extends Activity{
    
    private TabLayout tabLayout;
    private ViewPager viewPager;

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

        tabLayout = (TabLayout) findViewById(R.id.tablayout);
        viewPager = (ViewPager) findViewById(R.id.viewpager);

        List<String> titles = new ArrayList<>();
        titles.add("fragment1");
        titles.add("fragment2");
        
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new Tab1Fragment());
        fragments.add(new Tab2Fragment());

        FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager(), fragments, titles);
        viewPager.setAdapter(adapter);
        tabLayout.setTabTextColors(Color.BLACK, getResources().getColor(R.color.colorPrimary));//设置文字默认背景色和选中的背景色
        tabLayout.setupWithViewPager(viewPager);

    }

}


两个Fragment就省略了,随便写什么都可以的东西……


你可能感兴趣的:(android,组件,应用)