项目中需要用到Tablayout 自定义view ,花费了一些时间 ,现在我把方法公布一下,希望帮到大家.
View childView = null; for (int i = 0; i < mTitles.length; i++) {
//把tablayout的默认view换成你想要的布局 mTablayout.getTabAt(i).setCustomView(getTabView(i)); childView = mTablayout.getTabAt(i).getCustomView(); if (i == 0) { TextView tabViewDefault = (TextView) mTablayout.getTabAt(0).getCustomView().findViewById(R.id.tabText); tabViewDefault.setTextColor(Color.parseColor("#779dff"));
//初始化默认tab 使他颜色设置成选中状态 } }
//为tablayout增加点击事件 在选中的时候让他变色, 在没选中的时候使他变成黑色 mTablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { final TextView textView = (TextView) tab.getCustomView().findViewById(R.id.tabText); textView.setTextColor(Color.parseColor("#779dff")); } @Override public void onTabUnselected(TabLayout.Tab tab) { final TextView textView = (TextView) tab.getCustomView().findViewById(R.id.tabText); textView.setTextColor(Color.parseColor("#393939")); } @Override public void onTabReselected(TabLayout.Tab tab) { } }); }
//这个是你想要的tabview public View getTabView(int position) { //获得view View v = LayoutInflater.from(this).inflate(R.layout.tab_view_main, null); TextView tv = (TextView) v.findViewById(R.id.tabText); tv.setText(mTitles[position]); tv.setTypeface(Typeface.createFromAsset(getAssets(), "GOTHICB_1.TTF")); return v; }
<android.support.design.widget.TabLayout android:id="@+id/tablayout" android:layout_width="324dp" android:layout_height="48dp" app:tabGravity="fill" app:tabIndicatorHeight="1dp" app:tabMode="fixed" app:tabTextColor="#393939" app:tabIndicatorColor="#779DFF" app:tabSelectedTextColor="#779DFF" app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"/>
(1)app:tabMode有两个值:fixed和scrollable。 tab的滑动模式
(2)app:tabGravity有两个值:fill和center。 t而app:tabGravity设置值center,在有些情况下,比如TabLayout中子view较少需要居中显示时候的情景。
(3) 自由指定大小写的情况 增加这行就能让tablayout不再总是保持大小写
<style name="TextAppearance.Widget.TabWidget"> <item name="textSize">16sp</item> <item name="textStyle">normal</item>