andriod实战项目开发五----TabLayout自定义,完美解决选中标题后可以设置颜色和字体的大小

项目开发的需求:实现TabLayout样式的自定义。如果单纯的修改和跳转标题的颜色及指示器的样式,可以不需要自定义;如果需要选中标题后改变字体的大小,则需要自定义tablayout样式。

1. 布局文件如下

 

2.  增加tab_item.xml样式



    

3. Fragement 初始化tab数据

private void initView() {
        mTableLayout = (TabLayout) getActivity().findViewById(R.id.mTableLayout);

        // 添加tab初始化
        for (int i = 0; i < mTitles.length; i++) {
            TabLayout.Tab tab = mTableLayout.newTab();
            // 设置Tab的自定义View
            tab.setCustomView(R.layout.tab_item);
            // 添加Tab
            //tab.setText(mTitles[i]);
            mTableLayout.addTab(tab);

            // 设置tab_item 里的文字
            TextView textView = (TextView) tab.getCustomView().findViewById(R.id.tab_text);
            textView.setText(mTitles[i]);//设置tab上的文字
            if(i==0){
                textView.setTextColor(Color.BLACK);
                textView.setTextSize(18);
            }else {
                textView.setTextColor(Color.parseColor("#999999"));
                textView.setTextSize(16);
            }
        }

    }

4.  选中改变标题字体大小,在监听函数中实现

public void onActivityCreated(@NonNull Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Set the status bar color to transparent
        initView();
        mTableLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                TextView tabTextView = tab.getCustomView().findViewById(R.id.tab_text);
                tabTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                tabTextView.setTextColor(ContextCompat.getColor(mContext, R.color.black));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView tabTextView = tab.getCustomView().findViewById(R.id.tab_text);
                tabTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
                tabTextView.setTextColor(ContextCompat.getColor(mContext, R.color.color_999));
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

5.  达到实现效果图。andriod实战项目开发五----TabLayout自定义,完美解决选中标题后可以设置颜色和字体的大小_第1张图片

你可能感兴趣的:(gitee,android)