2017-06-17 10 views
0


ダイナミックカラーで丸みを帯びた背景を持つTextViewを作成する必要があります。
drawable背景を作成する方法はわかっていますが、コード内の色を変更する方法はわかりません。Android:TextViewの描画可能な背景の色をJavaコードで動的に変更する方法

描画可能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> 


のTextViewレイアウトXMLで:Javaファイルのコード内

<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" /> 

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. 


} 

私は必要なものがにあります012の場合、ドロアブルバックグラウンドの色を変更します(Textviewではなく)。

答えて

2

あなたはこのようにこれを行うことができます:

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

これが(ちょうど私の心から、テストされていない)動作するはずです! ドロアブルの色を変更した後にドロアブルをリセットするだけです。

0

別々の2つのドロアブルを作成し、それに応じて切り替えることもできます。

関連する問題