【问题标题】:TabLayout set tab background states programmaticallyTabLayout 以编程方式设置选项卡背景状态
【发布时间】:2018-01-27 05:38:49
【问题描述】:

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

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

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

【问题讨论】:

  • 您可以通过tabLayout.getTabAt(position).getCustomView()访问TabView实例
  • @NileshSingh 结果与上图相同。

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


【解决方案1】:
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());
    }
}

【讨论】:

    猜你喜欢
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多