通过mainactivity动态更改Drawable文件

时间:2017-10-27 10:13:05

标签: android background textview android-drawable

我的问题如下:

我有一个 Mainactivity 类,我有一个方法,它带有一个 TextView id colorselected

主要活动方法:

  @Override
public void onColorSelected(int dialogId, @ColorInt int color) {
    this.color = color;
     findViewById(R.id.colorselected).setBackgroundColor(color);
    //om te tonen welke kleur geselecteerd is
}

我的第一个XML文件中的TextView:

<TextView
    android:id="@+id/colorselected"
    android:layout_width="15dp"
    android:layout_height="15dp"
    android:background="@drawable/colorselecteddrawable"
    ... />

正如您所看到的 TextView 使用名为 colorselecteddrawable 的可绘制内容,该drawable中的代码为:

 <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <corners android:radius="50dp"/>
    <solid android:color="#000000" />

</shape>

每当执行onColorSelected-method时,我都会尝试设置 TextView 的背景颜色。但是,如果我现在使用该方法,我的 TextView 不再是圆形,可能是因为 TextView-backgroundcolor 覆盖,不再使用drawable了。

所以我的问题是:如何更改 Mainactivity 方法,以便每当方法执行时我都可以将<solid android:color="..."/>标记更改为新颜色?

1 个答案:

答案 0 :(得分:1)

您应该在xml代码中添加android:shape="rectangle"android:shape="oval"

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle">

    <corners android:radius="50dp"/>
    <solid android:color="#000000"/>

</shape>