TabLayout以编程方式设置选项卡背景状态

时间:2018-01-26 00:42:09

标签: android android-tablayout android-design-library

我正在尝试通过代码在TabLayout内设置不同状态的自定义视图背景。

有几个类似标题的问题,但它们处理的是XML。

据我所知,mTabBackgroundResId仅通过XML设置,并在创建时应用于TabView。但是,由于我使用自定义视图,因此不适用。通过代码或XML在自定义视图上设置背景只会产生如下内容:

enter image description here

1 个答案:

答案 0 :(得分:0)

public class MyTabLayout extends TabLayout {
    private LinearLayout linearLayout;

    private void init(Context context, attrs etc.) {
        linearLayout = (LinearLayout) getChildAt(0);
    }

    private StateListDrawable getStateListDrawable() {
        StateListDrawable sld = new StateListDrawable();
        sld.addState(new int[] {android.R.attr.state_pressed},
            ContextCompat.getDrawable(context, <color_id>);
        sld.addState(new int[] {android.R.attr.state_selected},
            ContextCompat.getDrawable(context, <color_id>);
        sld.addState(new int[] { },
            ContextCompat.getDrawable(context, <color_id>);
        return sld;
    }

    public void addTab(String label) {
        addTab(newTab().setCustomView(<view> or <view_id>);
        linearLayout.getChildAt(linearLayout.getChildCount()-1)
            .setBackground(getStateListDrawable());
    }
}
相关问题