通常,android.support.design.widget.TabLayout与Android的ViewPager联合使用,实现与ViewPager的切换与联动。
(1)比如,当用户手指触摸选择TabLayout中的某一项时候,ViewPager应当自动切换跳转到相应的Page页面;
(2)同样,当用户在翻动ViewPager时候,TabLayout也会自动的滚动到与当前ViewPager页面像对应的子item tab并使该子item tab处于选中状态。
测试用的主Activity MainActivity.java :
package com.zzw.testtablayout;
import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends Activity {
private final int COUNT = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(new MyAdapter(this));
// TabLayout和ViewPager双向、交互联动。
tabLayout.setupWithViewPager(viewPager);
}
private class MyAdapter extends PagerAdapter {
private Activity activity;
public MyAdapter(Activity activity) {
this.activity = activity;
}
@Override
public CharSequence getPageTitle(int position) {
return "选项" + position;
}
@Override
public Object instantiateItem(View container, int position) {
TextView tv = new TextView(activity);
tv.setText("ViewPager" + position);
tv.setTextSize(30.0f);
tv.setGravity(Gravity.CENTER);
((ViewGroup) container).addView(tv);
return tv;
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
@Override
public int getCount() {
return COUNT;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
}
MainActivity.java需要的布局文件:activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- app:tabIndicatorColor 指示器(字体下面的那一个横)显示颜色 -->
<!-- app:tabSelectedTextColor 选中的字体颜色 -->
<!-- app:tabTextColor 未选中的字体颜色 -->
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#26c6da"
app:tabSelectedTextColor="#f44336"
app:tabTextColor="#bdbdbd" />
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>