最近CS更新导致有段时间没有写博客了,今天谈谈design里面的指示器tablayout;由于系统带的指示器很丑,业务需就引入了design里面的指示器。
//导入design依赖、
dependencies { compile 'com.android.support:appcompat-v7:25.2.0' //design依赖 compile 'com.android.support:design:25.2.0' //注意你导入的design版本要和当前的V7版本一致(至少25要一致)XML代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.viewpagerdemo.MainActivity"> <android.support.design.widget.TabLayout android:id="@+id/tl" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <android.support.v4.view.ViewPager android:layout_below="@id/tl" android:id="@+id/vp" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
//适配器代码
List<String> title = new ArrayList<>(); Context context; //获取数据 public MyPagerAdapter(Context context) { this.context = context; for (int i = 1; i < 7; i++) { title.add("图片" + i); //指示器的内容 @Override public CharSequence getPageTitle(int position) { return title.get(position); }//mainactivity代码
//注意不要倒错包(很容易导到tableLayout) TabLayout tabLayout; ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { tabLayout = (TabLayout) findViewById(R.id.tl); viewPager = (ViewPager) findViewById(R.id.vp); //设置适配器 viewPager.setAdapter(new MyPagerAdapter(this)); //把指示器和viewpager关联起来 tabLayout.setupWithViewPager(viewPager); //设置指示器的标题样式 ; // TabLayout.MODE_FIXED为默认;TabLayout.MODE_SCROLLABLE可以滑动 tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE); //改变指示器颜色 tabLayout.setSelectedTabIndicatorColor(getResources().getColor(android.R.color.holo_blue_bright)); //改变指示器高 tabLayout.setSelectedTabIndicatorHeight(5); //改变背景颜色 tabLayout.setBackgroundColor(Color.WHITE); //改变选中字体颜色(没有选中的颜色,和选中的颜色) tabLayout.setTabTextColors(Color.GRAY,Color.BLUE); }
//最后上效果图