2014-10-20 75 views
0

有按鈕的選擇文件:如何重用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

回答

1

看到這些代碼的摘錄可以幫助你

創建圖形運行

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

相關問題