2012-08-15 9 views

risposta

-2

Basta usare setBackgroundColor;)

Aggiornamento: Anche qui è una grande scelta. Standard Android Button with a different color

p.s. perché dare downvote per aiuto?

+12

-1 Perché setBackgroundColor cambierebbe lo sfondo del pulsante, e non il colore on/off di ToggleButton, che è quello che è stato chiesto. – you786

20

Creare un XML denominato colors.xml in res/Valori cartella:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <color name="red">#ff0000</color> 
    <color name="green">#00ff00</color> 
</resources> 

In cartella drawable, creare un file xml my_btn_toggle.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_checked="false" android:drawable="@color/red" /> 
    <item android:state_checked="true" android:drawable="@color/green" /> 
</selector> 

e nella sezione XML definiscono la vostra ginocchiera pulsante:

<ToggleButton 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="New ToggleButton" 
    android:id="@+id/toggleButton" 
    android:background="@drawable/my_btn_toggle"/> 
+2

Questo non dà un risultato molto buono, poiché sovrasta la forma rettangolare del pulsante standard. –

+1

Questo cambia l'intero pulsante in verde/rosso. Non il colore di evidenziazione. –

+0

Questa soluzione non funziona sui temi più recenti. –

2
ToggleButton Btn=new ToggleButton(this);// or get it from the layout by ToggleButton Btn=(ToggleButton) findViewById(R.id.IDofButton); 
     Btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 

      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
       // TODO Auto-generated method stub 
       if(isChecked) 
        buttonView.setBackgroundColor(Color.GREEN); 
       else buttonView.setBackgroundColor(Color.RED); 
      } 
     }); 
Problemi correlati