2016-06-28 16 views
2

私はstate_selected = trueの背景として円を設定するセレクタがありますが、オブジェクトをクリックすると色を変更したいと思います。どうしたらいいですか?Android - Drawableの色を変更する

<shape xmlns:android="http://schemas.android.com/apk/res/android" 
android:shape="rectangle"> 
<solid android:color="#D0021B"/> 
<stroke android:width="2dp" android:color="#910012" /> 
<size 
    android:width="50dp" 
    android:height="50dp" /> 
<corners android:radius="50dp" /> 
</shape> 

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:drawable="@android:color/black" android:state_selected="false" /> 
<item android:drawable="@drawable/nav_circle" android:state_selected="true" /> 
</selector> 
+0

使用はstate_pressed .....私も動的にする色を設定するにはどうすればよい –

+0

? – Mikerizzo

答えて

0

あなたはプログラム的にそれを行うことができます。

public static void colorDrawable(View view, int color) { 
      Drawable wrappedDrawable = DrawableCompat.wrap(view.getBackground()); 
      if (wrappedDrawable != null) { 
       DrawableCompat.setTint(wrappedDrawable.mutate(), color); 
       setBackgroundDrawable(view, wrappedDrawable); 
      } 
     } 

@TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
public static void setBackgroundDrawable(View view, Drawable drawable) { 

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { 
     view.setBackgroundDrawable(drawable); 
    } else { 
     view.setBackground(drawable); 
    } 
} 
0

あなたはそれを押した瞬間に色を変更したい場合は、あなたがstate_pressed使用することができます。

これは私のドローアブルが設定されている方法です。

<item android:state_pressed="true" 
     android:drawable="@color/pressedColor"/> <!-- pressed state --> 
<item android:state_focused="true" 
     android:drawable="@color/pressedColor"/> <!-- focused state --> 
<item android:drawable="@color/colorPrimary"/> 

あなたもアンドロイドの下に別の描画可能使用することができます:あなたはそれが押されたときに背景描画可能を変更したい場合は、別のボタンの背景を変更することができ、

<item android:state_pressed="true" 
     android:drawable="@drawable/button_solid"/> 

しかし描画可能属性を描画可能なXML

button.setBackground(getDrawable(R.drawable.selectorDrawable2)); 
+0

サーバから来る動的な色を設定する必要があります – Mikerizzo

0

は多分これはあなたを助ける:

i=(ImageView)findViewById(R.id.image); 
    i.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      i.getBackground().setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP); 
     } 
    }); 

ImageViewのXMLコード:

<ImageView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="@drawable/nav_circle" 
    android:layout_centerVertical="true" 
    android:layout_centerHorizontal="true" 
    android:id="@+id/image" /> 
+0

android.graphics.drawable.StateListDrawableを取得するとandroid.graphics.drawable.GradientDrawableエラー – Mikerizzo

+0

にキャストできません。 getBackground()。setColorFilter(Color.BLUE、PorterDuff.Mode.SRC_ATOP); 'また、私のXMLコードを見ることができますか? –

関連する問題