【问题标题】:How to set layout background tint from string programmatically?如何以编程方式从字符串设置布局背景色调?
【发布时间】:2018-05-29 23:10:54
【问题描述】:

我试过这段代码:

LinearLayout someLayout=(LinearLayout)view.findViewById(R.id.someLayout);
        someLayout.setBackgroundTintList(context.getResources().getColorStateList(Color.parseColor("#ff8800")));

但我收到一个错误:android.content.res.Resources$NotFoundException 我从外部源获取颜色十六进制,因此无法将其嵌入到 colors.xml 中。 另外我想改变色调,而不是背景,所以 setBackground 不是一个选项。

【问题讨论】:

标签: android layout colors hex android-linearlayout


【解决方案1】:

我想我不能使用 getColorStateList() 所以我寻找另一种方法来做到这一点。 最后,我可以使用以下代码设置颜色:

LinearLayout someLayout=(LinearLayout)view.findViewById(R.id.someLayout);
        someLayout.getBackground().setColorFilter(Color.parseColor("#ff8800"), PorterDuff.Mode.SRC_ATOP);

这就像我更改了 xml 文件中的 backgroundTint 属性一样,因此非常适合我的问题。

【讨论】:

    【解决方案2】:

    我能够使用以下行进行管理。根据你的情况改变它。

    myView.getBackground().setTint(currentView.getResources().getColor(R.color.colorAccent));
    

    【讨论】:

      【解决方案3】:

      对于 Kotlin , 我修改了@Krestek 的答案:

      someLayout.background.setColorFilter(Color.parseColor("#ff8800"), PorterDuff.Mode.SRC_ATOP)
      

      【讨论】:

        【解决方案4】:

        您不能这样做,因为 getColorStateList 方法需要资源的 int id,而您正在传递 RGB 颜色 int。您应该在此 link

        之后创建颜色状态列表

        然后这样设置:

        .getColorStateList(R.color.your_xml_name)
        

        【讨论】:

        • 是的,我想到了,所以我用了其他方法。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-18
        • 2023-03-26
        • 2014-06-24
        • 2017-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多