Android高级UI之ViewPager实现页卡的最新方法-简洁的TabLayout

1 概述

Google在2015的IO大会上,给开发者们带来了全新的Android Design Support Library,里面包含了许多新控件,这些新控件有许多是把以前的一些第三方开源库官方化,实现起来更为简便,简直是开发者的福音。TabLayout 便是其中之一, TabLayout控件是用于选项卡切换。

使用TabLayout实现底部Tab布局

GitHub-MaterialDesignExample

TabLayout+ViewPager 简单实现app底部Tab布局

android design library提供的TabLayout的用法

ViewPager实现页卡的最新方法–简洁的TabLayout(谷歌支持包)

2 作用

2.1 实现标题栏

代替了第三方控件:ViewPagerIndicator 、SlidingTabStrip、自定义标题栏等方法。

2.2 实现底部栏

代替了:RadioGroup+FrameLayout、TabHost/RadioButton+Fragment+FragmentPagerAdapter+ViewPager等方法。

3 底部栏实现

3.1 添加依赖包

compile 'com.android.support:design:23.1.1'

3.2 布局

3.2.1 根布局。下面我们开始实现底部Tab,layout布局比较简单,我们只用把TabLayout放置在底部即可,activity_bottom_tab.xml

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1.0"
            android:scrollbars="none" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            style="@style/MyCustomTabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

</LinearLayout>

定义了一个自定义的style


<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabMaxWidth">@dimen/tab_max_width</item>
    <item name="tabIndicatorColor">?attr/colorAccent</item>
    <item name="tabIndicatorHeight">2dp</item>
    <item name="tabPaddingStart">12dp</item>
    <item name="tabPaddingEnd">12dp</item>
    <item name="tabBackground">?attr/selectableItemBackground</item>
    <item name="tabTextAppearance">@style/MyCustomTabTextAppearance</item>
    <item name="tabSelectedTextColor">?android:textColorPrimary</item>
</style>

<style name="MyCustomTabTextAppearance" parent="TextAppearance.Design.Tab">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?android:textColorSecondary</item>
    <item name="textAllCaps">true</item>
</style>

3.2.2 低栏每个item布局,custom_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent">

    <ImageView  android:layout_marginTop="2dp" android:id="@+id/imageView" android:src="@mipmap/ic_launcher" android:layout_width="25dp" android:layout_height="25dp" />

    <TextView  android:id="@+id/textView" android:layout_marginTop="2dp" android:textSize="14sp" android:textColor="@color/tab_text" android:layout_width="wrap_content" android:layout_height="wrap_content" />

</LinearLayout>

3.3 代码实现

BottomTabActivity.xml

/** * Created by chenliguan on 16/4/7 */
public class BottomTabActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private TabLayout tabLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bottom_tab);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(R.string.title_buttom_tab);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        //重点代码
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);

        SampleFragmentPagerAdapter pagerAdapter =
                new SampleFragmentPagerAdapter(getSupportFragmentManager(), this);
        viewPager.setAdapter(pagerAdapter);//1.设置好ViewPager
        tabLayout.setupWithViewPager(viewPager);//2.设置TabLayout与ViewPager的对应关系
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(pagerAdapter.getTabView(i));//(最关键)3.使用TabLayout的setCustomView设置自定义的TAB_View
            }
        }
        viewPager.setCurrentItem(1);
    }

    /** * 自定义低栏适配器(文字+图片) */
    public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
        final int PAGE_COUNT = 3;
        private String tabTitles[] = new String[]{"TAB1", "TAB2", "TAB3"};
        private Context context;

        public View getTabView(int position) {
            View v = LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
            TextView tv = (TextView) v.findViewById(R.id.textView);
            tv.setText(tabTitles[position]);
            ImageView img = (ImageView) v.findViewById(R.id.imageView);
            //img.setImageResource(imageResId[position]);
            return v;
        }

        public SampleFragmentPagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
        }

        @Override
        public int getCount() {
            return PAGE_COUNT;
        }

        @Override
        public Fragment getItem(int position) {
            return PageFragment.newInstance(position + 1);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabTitles[position];
        }
    }

    /** * 默认适配器 */
    public static class PageFragment extends Fragment {
        public static final String ARG_PAGE = "ARG_PAGE";

        private int mPage;

        public static PageFragment newInstance(int page) {
            Bundle args = new Bundle();
            args.putInt(ARG_PAGE, page);
            PageFragment fragment = new PageFragment();
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mPage = getArguments().getInt(ARG_PAGE);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_page, container, false);
            TextView textView = (TextView) view;
            textView.setText("Fragment #" + mPage);
            return view;
        }
    }

}

3.4 效果图

Android高级UI之ViewPager实现页卡的最新方法-简洁的TabLayout_第1张图片

4 标题栏实现

4.1 添加依赖包

compile 'com.android.support:design:23.1.1'

4.2 布局

activity_five.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">

    <android.support.design.widget.TabLayout  android:id="@+id/tabs" style="@style/MyCustomTabLayout" android:layout_width="match_parent" android:layout_height="wrap_content"/>

    <!--可滑动的布局内容-->
    <android.support.v4.view.ViewPager  android:id="@+id/vp_view" android:layout_width="match_parent" android:layout_height="wrap_content"/>
</LinearLayout>

定义了一个自定义的style


<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabMaxWidth">@dimen/tab_max_width</item>
    <item name="tabIndicatorColor">?attr/colorAccent</item>
    <item name="tabIndicatorHeight">2dp</item>
    <item name="tabPaddingStart">12dp</item>
    <item name="tabPaddingEnd">12dp</item>
    <item name="tabBackground">?attr/selectableItemBackground</item>
    <item name="tabTextAppearance">@style/MyCustomTabTextAppearance</item>
    <item name="tabSelectedTextColor">?android:textColorPrimary</item>
</style>

<style name="MyCustomTabTextAppearance" parent="TextAppearance.Design.Tab">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?android:textColorSecondary</item>
    <item name="textAllCaps">true</item>
</style>

4.3 代码实现

FiveActivity.java

public class FiveActivity extends Activity {
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private LayoutInflater mInflater;
    private List<String> mTitleList = new ArrayList<>();//页卡标题集合
    private View view1, view2, view3, view4, view5;//页卡视图
    private List<View> mViewList = new ArrayList<>();//页卡视图集合

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

        mViewPager = (ViewPager) findViewById(R.id.vp_view);
        mTabLayout = (TabLayout) findViewById(R.id.tabs);

        mInflater = LayoutInflater.from(this);
        view1 = mInflater.inflate(R.layout.activity_main, null);
        view2 = mInflater.inflate(R.layout.activity_main, null);
        view3 = mInflater.inflate(R.layout.activity_main, null);
        view4 = mInflater.inflate(R.layout.activity_main, null);
        view5 = mInflater.inflate(R.layout.activity_main, null);
        //添加页卡视图
        mViewList.add(view1);
        mViewList.add(view2);
        mViewList.add(view3);
        mViewList.add(view4);
        mViewList.add(view5);
        //添加页卡标题
        mTitleList.add("No:1");
        mTitleList.add("No:2");
        mTitleList.add("No:3");
        mTitleList.add("No:4");
        mTitleList.add("No:5");

        MyPagerAdapter mAdapter = new MyPagerAdapter(mViewList);
        mViewPager.setAdapter(mAdapter);//1.给ViewPager设置适配器
        mTabLayout.setupWithViewPager(mViewPager);//2.将TabLayout和ViewPager关联起来。
        mTabLayout.setTabsFromPagerAdapter(mAdapter);//3.给Tabs设置适配器
    }


    //ViewPager适配器
    class MyPagerAdapter extends PagerAdapter {
        private List<View> mViewList;

        public MyPagerAdapter(List<View> mViewList) {
            this.mViewList = mViewList;
        }

        @Override
        public int getCount() {
            return mViewList.size();//页卡数
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;//官方推荐写法
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewList.get(position));//添加页卡
            return mViewList.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));//删除页卡
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitleList.get(position);//页卡标题
        }
    }
}

4.4 效果图

Android高级UI之ViewPager实现页卡的最新方法-简洁的TabLayout_第2张图片

你可能感兴趣的:(android)