如何重用android中颜色不同按钮的选择器?

如何重用android中颜色不同按钮的选择器?

问题描述:

有按钮的选择文件:如何重用android中颜色不同按钮的选择器?

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

<item android:state_pressed="true"> 
    <shape> 
     <solid android:color="#686b70"/> 

     <stroke android:width="1dip" android:color="#595b61" /> 

     <corners android:radius="8dip" /> 
    </shape> 
</item> 

<item android:state_focused="true"> 
    <shape> 
     <solid android:color="#686b70"/> 

     <stroke android:width="1dip" android:color="#595b61" /> 

     <corners android:radius="8dip" /> 
    </shape> 

</item> 
<item> 
    <shape> 
     <solid android:color="#868c95"/> 

     <stroke android:width="1dip" android:color="#7c818b" /> 

     <corners android:radius="8dip" /> 
    </shape> 
</item> 

我只需要改变的固体和中风的android:color创建一个新的选择。所以我想知道是否有任何方法来重用这个选择器的颜色不同的按钮。

+0

您需要以编程方式使用java代码创建选择器和形状。 – 2014-10-20 12:26:26

+0

@BirajZalavadia xml不能做到这一点? – zzy 2014-10-20 12:27:05

+0

正如你所说你想动态。而xmls在编译时。你不能在运行时写入xml。 – 2014-10-20 12:28:52

看到这些代码的摘录可以帮助你

创建图形运行

ShapeDrawable shapeSelected = new ShapeDrawable(new RectShape()); 
     shapeSelected.getPaint().setColor(Color.RED); 
     shapeSelected.getPaint().setStyle(Paint.Style.STROKE); 
     shapeSelected.getPaint().setStrokeWidth(1); 

     ShapeDrawable shapeNormal = new ShapeDrawable(new RectShape()); 
     shapeSelected.getPaint().setColor(Color.WHITE); 
     shapeSelected.getPaint().setStyle(Paint.Style.STROKE); 
     shapeSelected.getPaint().setStrokeWidth(1); 

在运行时创建选择

StateListDrawable states =new StateListDrawable(); 
    Resources res = getResources(); 
    states.addState(new int[] {android.R.attr.state_pressed},shapeSelected); 
    states.addState(new int[] {android.R.attr.state_focused}, shapeSelected); 
    states.addState(new int[] {}, shapeNormal); 

设为您的看法背景

yourButton.setBackground(states); 
+0

只是一个小实现:https://gist.github.com/creativepsyco/8c2d05803a5193c187ef – redDragonzz 2015-01-13 14:06:59