tablayout修改成自定义字体,自由大小写

本文介绍了一种在项目中自定义TabLayout的方法,包括替换默认视图、设置文本样式及响应点击事件等步骤,帮助开发者实现更加灵活的TabLayout布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中需要用到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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值