Design下的TabLayout和Fragment和ViewPager聯動的簡單使用

首先介紹下TabLayout,實際開發中我們經常需要用到Viewpager,而已需要跟頭部的Tab實現聯動效果。而Design的出現,給我們一種更加方便的UI框架去實現這種效果。今天就介紹它與Viewpager和Fragment之間的聯動效果。首先需要先有design包:

之後我們的build.gradle文件下多了這樣一句代碼就ok啦。

然後接下就是佈局文件:activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabTextColor="#00f"
        app:tabSelectedTextColor="#f00"
        app:tabIndicatorColor="#0373b4"
        app:tabIndicatorHeight="5dp"
        app:tabMode="scrollable" />


    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager_main"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

同樣這裏需要在根標籤下加入TabLayout的命名空間

xmlns:app="http://schemas.android.com/apk/res-auto"
下面我來介紹下它每個屬性所代表的意思:

app:tabTextColor="#00f"
顧名思義,這個表示的是Tab上字體的顏色

app:tabSelectedTextColor="#f00"
這個屬性表示Tab上選中後字體的顏色

app:tabIndicatorColor="#0373b4"
這個表示Tab的指示條的顏色

app:tabIndicatorHeight="5dp"
這個表示Tab指示條的高度

app:tabMode="scrollable"
這個表示Tab的模式。


因爲我們今天這個例子需要用到ViewPager 和Fragment.所以下面的是Fragment的類和佈局文件。

首先是fragment.


public class MyFragment extends ListFragment {
    private final static String TAG = "DummyFragment";

    private TextView tvInfo;
    private ListView listView_dummy;
    private int tabindex = 0;
    private List<Map<String, Object>> totalList = new ArrayList<Map<String, Object>>();

    public static MyFragment getInstance(int tabindex) {
        MyFragment fragment = new MyFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("tabindex", tabindex);
        fragment.setArguments(bundle);
        return fragment;
    }

    // 數據初始化
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        tabindex = bundle.getInt("tabindex");

        // 模擬一個加載數據的方法
        totalList = loadNetworkData();
    }

    // 真實場景中應該訪問網絡,json解析,返回list
    private List<Map<String, Object>> loadNetworkData() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < 20; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("icon", R.mipmap.ic_launcher);
            map.put("username", "username_" + tabindex + "_" + i);
            map.put("number", "12345_" + tabindex + "_" + i);
            list.add(map);
        }
        return list;
    }

    // 負責加載ui
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dummy, container, false);
        tvInfo = (TextView) view.findViewById(R.id.textView_dummy_info);
        tvInfo.setText("您點擊了第" + tabindex + "個書籤");

        SimpleAdapter adapter = new SimpleAdapter(getActivity(), totalList, R.layout.item_dummyfragment, new String[]{"icon", "username", "number"}, new int[]{R.id.imageView_item_icon, R.id.textView_item_username, R.id.textView_item_number});
        setListAdapter(adapter);
        return view;
    }

}

下面是fragment的xml文件:

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

    <TextView
        android:id="@+id/textView_dummy_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#000"
        android:textColor="#fff"
        android:text="TextView" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

    <TextView
        android:id="@android:id/empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="暫無數據!" />

</LinearLayout>

然後纔是我們的MainActivity

public class MainActivity extends AppCompatActivity {
    private TabLayout tabLayout_main;
    private ViewPager viewPager;
    private List<Fragment> fragments = new ArrayList<Fragment>();

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

        findViews();
        initViewPager();
        initTabs();
    }

    private void initViewPager() {
        String[] arrTabTitles = getResources().getStringArray(R.array.arrTabTitles);

        for (int i = 0; i < arrTabTitles.length; i++) {
//            tabLayout_main.newTab().setIcon(R.mipmap.ic_launcher);

            MyFragment fragment = MyFragment.getInstance(i + 1);
            fragments.add(fragment);
        }
        viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), fragments, arrTabTitles));
    }

    private void findViews() {
        tabLayout_main = (TabLayout) findViewById(R.id.tabLayout_main);
        viewPager = (ViewPager) findViewById(R.id.viewPager_main);
    }

    private void initTabs() {
        tabLayout_main.setupWithViewPager(viewPager);
//        tabLayout_main.setSelectedTabIndicatorColor(Color.parseColor("#ff0373b4"));
//        tabLayout_main.setSelectedTabIndicatorHeight(10);
//        tabLayout_main.setTabTextColors(Color.parseColor("#ff000000"), Color.parseColor("#ffff0000"));
//        tabLayout_main.setSoundEffectsEnabled(true);
        //tabLayout_main.setSmoothScrollingEnabled(false);
    }
}
String[] arrTabTitles = getResources().getStringArray(R.array.arrTabTitles);
這裏是從資源文件中得到之前定義好的字符串數組文件,這裏也貼下

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="arrTabTitles">
        <item>要聞</item>
        <item>視頻</item>
        <item>娛樂</item>
        <item>體育</item>
        <item>財經</item>
        <item>科技</item>
        <item>社會</item>
        <item>軍事</item>
        <item>遊戲</item>
    </string-array>

</resources>

注意,之前我們在佈局文件中爲TabLayout設置的屬性我們在代碼中也可以動態設置,

//tabLayout_main.setSelectedTabIndicatorColor(Color.parseColor("#ff0373b4"));
//        tabLayout_main.setSelectedTabIndicatorHeight(10);
//        tabLayout_main.setTabTextColors(Color.parseColor("#ff000000"), Color.parseColor("#ffff0000"));
//        tabLayout_main.setSoundEffectsEnabled(true);
        //tabLayout_main.setSmoothScrollingEnabled(false);
這裏我們的ViewPager需要用到Adapter.下面是Adapter。

public class MyPagerAdapter extends FragmentPagerAdapter {
	private List<Fragment> fragments = null;
    private String[] tabTitles = null;

	public MyPagerAdapter(FragmentManager fm, List<Fragment> fragments , String[] arrTabTitles) {
		super(fm);
		this.fragments = fragments;
		this.tabTitles = arrTabTitles;
	}

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

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

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

}

需要注意的是MainActivity中的TabLayout需要調用
setupWithViewPager()
該方法使Tab跟ViewPager關聯起來。

而Adapter中也需要重寫getPageTitle()方法。返回選中哪個頁面對應的Tab.

這樣就OK了。一個簡單的TabLayout結合ViewPager和Fragment的聯動效果就搞定了。是不是很簡單。現在我們看下效果圖




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章