【问题标题】:android change shape color used in custom radio button programmaticallyandroid以编程方式更改自定义单选按钮中使用的形状颜色
【发布时间】:2019-07-13 01:43:39
【问题描述】:

我使用以下代码创建自定义单选按钮:

layout.xml

<RadioButton
        android:id="@+id/radio0"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:background="@drawable/control_radio_button"
        android:button="@android:color/transparent"
        android:checked="false" />

@drawable/control_radio_button

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/control_radio_bg_false" android:state_checked="true" android:state_pressed="true" />
    <item android:drawable="@drawable/control_radio_bg_true" android:state_pressed="true" />
    <item android:drawable="@drawable/control_radio_bg_true" android:state_checked="true" />
    <item android:drawable="@drawable/control_radio_bg_false" />
</selector>

@drawable/control_radio_bg_true

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="999dp" />
    <stroke
        android:width="2dip"
        android:color="#E0E0E0" />
    <solid android:color="#f44336" />
</shape>

@drawable/control_radio_bg_true

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="999dp" />
    <stroke
        android:width="6dp"
        android:color="#bfbfbf" />
    <solid android:color="#f44336" />
</shape>

我可以通过编程更改@drawable/control_radio_bg_false@drawable/control_radio_bg_true 的背景吗?

我想使用适配器(在 recyclerview 中)创建具有不同颜色的自定义单选按钮列表。

我该怎么做?

【问题讨论】:

    标签: android kotlin radio-button custom-controls shapes


    【解决方案1】:

    您可以尝试以下方法:

    (radio0.background as? ShapeDrawable)?.apply {
        paint.color = ContextCompat.getColor(context, R.color.new_color)
    }
    

    您需要自己处理状态,但这应该涵盖您。

    【讨论】:

    • 我使用以下代码更改可绘制对象的背景:val sd: Drawable = ContextCompat.getDrawable(this, R.drawable.control_radio_bg_false)val gd: GradientDrawable = sd as GradientDrawablegd.setColor(ContextCompat.getColor(this, R.color.building_choose_image_option_blue)) 以及 R.drawbale.control_radio_bg_true,但之后代码无法在适配器中使用,因为添加的每个单选按钮都有蓝色颜色。我认为我们必须以编程方式制作所有ShapeDrawbale,然后在目标控件中设置为背景
    【解决方案2】:

    我对 kotlin 代码做了很多研究,发现了这一点。在此处添加此内容,以便如果其他人专门来寻找 kotlin。 添加可绘制形状作为视图的背景后,在相应的活动中添加以下代码。

    YourViewID.background.setColorFilter(Color.parseColor("#00000"),PorterDuff.Mode.SRC_OVER)
    

    【讨论】:

      猜你喜欢
      • 2016-10-11
      • 2019-05-20
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 2020-05-22
      • 2016-02-21
      • 2016-11-06
      • 2019-05-29
      相关资源
      最近更新 更多