TabLayout替换ViewPagerIndicator
TabLayout替换ViewPagerIndicator
参照文章: http://chenfuduo.me/2015/07/30/TabLayout-of-design-support-library/
1.build.gradle关联库,需要在联网的情况下做
compile 'com.android.support:design:22.2.1'
2.在布局文件中使用TabLayout,即把TabPagerIndicator替换成TabLayout
<android.support.design.widget.TabLayout
android:id="@+id/tabpage_indicator"
android:layout_width="wrap_content"
style="@style/MyCustomTabLayout"
android:layout_height="wrap_content"
android:layout_weight="1" />
3.设置样式(不能没有样式)
style="@style/MyCustomTabLayout"
<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
<item name="tabMaxWidth">@dimen/tab_max_width</item>
<item name="tabMinWidth">72dp</item>
<item name="tabIndicatorColor">#0000FF</item>
<item name="tabIndicatorHeight">3dp</item>
<item name="tabPaddingStart">8dp</item>
<item name="tabPaddingEnd">8dp</item>
<item name="tabBackground">@android:color/white</item>
<item name="tabTextAppearance">@style/MyCustomTabTextAppearance</item>
<item name="tabSelectedTextColor">@android:color/holo_red_light</item>
</style>
<style name="MyCustomTabTextAppearance" parent="TextAppearance.Design.Tab">
<item name="android:textSize">14sp</item>
<item name="android:textColor">@android:color/black</item>
<item name="textAllCaps">false</item>
</style>
4.关联ViewPager
//TabLayout关联ViewPager
tabLayout.setupWithViewPager(vp_news_menu_detail);
//一定要设置设置滚动模式
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
5.在适配器中重写getPageTitle方法
@Override
public CharSequence getPageTitle(int position) {
return children.get(position).getTitle();
}
6.自定义Tab的效果
6.1 设置Tab的效果步骤一,在适配器中重写getTabView()方法
public View getTabView(int position){
View view = LayoutInflater.from(mActivity).inflate(R.layout.tab_item, null);
TextView tv= (TextView) view.findViewById(R.id.textView);
tv.setText(children.get(position).getTitle());
ImageView img = (ImageView) view.findViewById(R.id.imageView);
img.setImageResource(R.drawable.dot_focus);
return view;
}
要写布局如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp" />
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true" />
</LinearLayout>
6.2调用 getTabView 方法
//自定义Table布局要结合适配器中的getTabView方法
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(mAdapter.getTabView(i));
}
如果不调用就没有效果
静以修身,俭以养德。
posted on 2016-09-28 13:44 miaozhenzhong 阅读(278) 评论(0) 编辑 收藏 举报