2016-04-03 37 views
4

如何根據當前的應用主題爲按鈕選擇器設置不同的樣式?如何爲按鈕選擇器設置不同的主題?

這裏是我的button_selector.xml

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

    <item android:state_pressed="true"> 
     <color android:color="@color/color_theme1"/> 
     </item> 
<!-- pressed --> 
    <item android:drawable="@color/transparent"/> 
<!-- default --> 

</selector> 
+0

顯而易見的答案是使用一個實際的主題色,而不是'@色/ color_theme1',例如像'colorPrimary'。這就是說,這將只適用於api 21或以上 –

回答

2

當你的應用程序的主題顏色是在color.xml color_primary。你可以像這樣在你的選擇器中使用它。但是你必須創建兩個可繪製文件,一個用於默認狀態,另一個用於selected_state。

button_selector.xml:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<!--selected/pressed/focused --> 
<item  android:state_selected="true" 
      android:drawable="@drawable/button_selected" 
      /> 
    <item android:drawable="@drawable/button_default"/> 
<!-- default --> 

</selector> 

button_default.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
<!--this is to give gradient effect --> 
<gradient android:angle="270" 
       android:startColor="@color/gray" 
       android:endColor="#@color/gray" 
       /> 
<!-- this will make corners of button rounded --> 
<corners android:topLeftRadius="5dip" 
       android:bottomRightRadius="5dip" 
       android:topRightRadius="5dip" 
       android:bottomLeftRadius="5dip"/> 

</shape> 

button_selected.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
<!--this is to give gradient effect --> 
<gradient android:angle="270" 
      android:startColor="@color/color_primary" 
      android:endColor="#@color/color_primary" 
      /> 
<!-- this wil make corners of button rounded --> 
<corners android:topLeftRadius="5dip" 
       android:bottomRightRadius="5dip" 
       android:topRightRadius="5dip" 
       android:bottomLeftRadius="5dip"/> 

</shape> 

您必須以編程方式執行以下操作,以便該按鈕將保持選中狀態。

button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       if(v.isSelected()) 
       { 
        v.setSelected(false); 
       } 
       else 
       { 
        v.setSelected(true); 
       } 
      } 
     }); 
+0

我只是想根據所選主題更改按鈕按下的顏色。 –

+0

謝謝,爲了您的澄清,您的實際問題是一些東西,但您提到在您的問題中使用樣式。編輯你的問題。請批准。 – HourGlass

1

在您的應用程序中使用動態選擇器,以便您可以根據您的要求分配顏色。

StateListDrawable states = new StateListDrawable(); 
states.addState(new int[] {android.R.attr.state_pressed}, 
    getResources().getDrawable(R.drawable.pressed)); 
states.addState(new int[] {android.R.attr.state_focused}, 
    getResources().getDrawable(R.drawable.focused)); 
states.addState(new int[] { }, 
    getResources().getDrawable(R.drawable.normal)); 
imageView.setImageDrawable(states); 

或者

檢查thisthis可以幫助你

+0

任何XML替代? –

相關問題