简体   繁体   中英

Android: How to change the color of the drawable background of TextView dynamically in the java code


I need to make TextView with rounded background with dynamic color.
I know how to make drawable background but I don't know how to change the color of it in the code?

the drawable bg xml:

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

    <item>
        <shape android:shape="rectangle" >
            <solid android:color="@color/colorPrimary"></solid>
<!-- I want to change this color dynamically in the java code --> 
            <corners android:radius="7dp"></corners>
        </shape>
    </item>


</selector>


the textview in the layout xml:

<TextView
            android:id="@+id/txt_taskTag"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/bg_rounded_solid"
            android:paddingEnd="10dp"
            android:paddingStart="10dp"
            android:text="work"
            android:textColor="#fff"
            android:layout_marginEnd="10dp"
            android:textSize="12sp" />

in the Java file code:

 public void onBindViewHolder(final ViewHolder holder, int position) {  

       holder.txt_taskCategory.setText(holder.mTask._catName);
       holder.txt_taskCategory.setBackgroundColor( Color.parseColor( holder.mTask._catColor));
    //when i do that it remove the drawable background and just color it.


}

What i need is to change the color of the drawable background (not the Textview) whith "holder.mTask._catColor"

You can do this like this:

Drawable drawable = getResources().getDrawable(R.drawable.bg_rounded_solid);
drawable.mutate().setColorFilter(color, PorterDuff.Mode.SRC_IN);
yourTextView.setBackground(drawable);

This should work (not tested, just from my mind)! Just reset the drawable once you change the color of it.

您还可以创建2个单独的可绘制对象并相应地进行切换。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM