Android

Anroid入门 -- Tab选项卡

2017-02-25  本文已影响307人  binni

实现方式

Android 实现Tab选项卡的方式非常多,印象当中就有这么几种:

  1. 传统的ViewPager
  2. FragmentManager + Fragment
  3. ViewPager + FragmentPagerAdapter
  4. TabPageIndicator + ViewPager + FragmentPagerAdapter

今天这里使用 TabLayout + ViewPager + FragmentPagerAdapter 的方式来实现

效果图

Android Tab

布局文件

** activity_main.xml **

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.binni.android_tab.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

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

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

** activity_main.xml 主窗口对应的xml布局文件;最外层使用CoordinatorLayout控件,头部使用AppBarLayout包裹TabLayout,再是ViewPager**,这是嵌套方式也是android studio创建tab类型应用的默认布局;

** fragment_main.xml **

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity$TabsFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_below="@+id/section_label"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="false" />

</RelativeLayout>

** fragment_main.xml **是给每一个切换的界面准备的布局文件

TabLayout

TabLayout的详细的用法请移步TabLayout的使用
这里我们只需要简单的使用<code>TabLayout.setupWithViewPager(ViewPager);</code>一行代码即可实现TabLayoutViewPager的组合与联动;

ViewPager

        public Fragment getItem(int position) 
        public int getCount() 
        public CharSequence getPageTitle(int position) 
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

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

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

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

代码很简介,完全不需要加注释,不是嘛,这里稍微讲一下addFragment这个自定义方法:
我们在FragmentPagerAdapter 类里增加了mFragmentListmFragmentTitleList 来管理Fragment,因此,需要增加addFragment方法供外部调用,实现Fragment的添加;这样的好处很明显,如果把Fragment以及相关内容放到Tab选项卡所在Activity(或者Fragment)中管理,会导致主Activity更臃肿,且不易管理,放到此处,实在是合适的不能再合适了!

**展现内容的TabsFragment **

    public static class TabsFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */

        View rootView;
        TextView textView;
        EditText editText;
        Button button;

        private static final String ARG_SECTION_NUMBER = "section_number";

        public TabsFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static TabsFragment newInstance(int sectionNumber) {
            TabsFragment fragment = new TabsFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            Log.d("ARG_SECTION_NUMBER:",getArguments().getInt(ARG_SECTION_NUMBER)+"");

            /**
             * 防止Fragment多次切换时调用onCreateView重新加载View
             */
            if (null == rootView) {
                rootView = inflater.inflate(R.layout.fragment_main, container, false);
            }

            //child controls init
            textView = (TextView) rootView.findViewById(R.id.section_label);
            editText=(EditText)rootView.findViewById(R.id.editText);
            button=(Button)rootView.findViewById(R.id.button);

            //缓存的rootView需要判断是否已经被加过parent, 如果有parent需要从parent删除,要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }

            return rootView;
        }

        @Override
        public void onResume() {
            super.onResume();
            Log.i("PatrolTaskDetail", "****>>>> onResume");
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            Date now = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//可以方便地修改日期格式
            String dateString = dateFormat.format( now );
            editText.setText("");

            button.setText(dateString);
            Log.d("dateString:",dateString);

            //initView();
        }

        @Override
        public void onHiddenChanged(boolean hidden) {
            Log.d("hidden:",hidden+"");
            Log.d("ARG_SECTION_NUMBER:",getArguments().getInt(ARG_SECTION_NUMBER)+"");
        }

        @Override
        public void onDestroyView(){
            super.onDestroyView();
            Log.d("onDestroyView:",getArguments().getInt(ARG_SECTION_NUMBER)+"");
        }
    }
上一篇下一篇

猜你喜欢

热点阅读