2012-06-30 14 views
129

Vorrei implementare un pulsante di commutazione, android.widget.Switch (disponibile dall'API v.14).android.widget.Switch - ascoltatore di eventi on/off?

<Switch 
    android:id="@+id/switch1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Switch" /> 

Ma non sono sicuro di come aggiungere un listener di eventi per il pulsante. Dovrebbe essere un ascoltatore "onclick"? E come potrei sapere se è attivato o meno?

+3

OnClick tramite XML funziona in realtà - ma solo per "clic" sul pulsante, non per "diapositive". – m02ph3u5

risposta

290

interruttore eredita CompoundButton 's attributi, quindi vi consiglio il OnCheckedChangeListener

mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
     // do something, the isChecked will be 
     // true if the switch is in the On position 
    } 
}); 
+0

Funziona come un fascino, grazie Sam – Johan

+1

@Johan Nessun problema. Non so voi, ma vorrei che lo chiamassero OnCheckChangedListener, simile a OnItemSelectedListener, dato che On-_Noun _-_ Verb_-Listener è una convocazione di nomi stabilita. – Sam

+5

Non funziona quando si preme a lungo il pulsante, quindi lo si fa scorrere/si sposta. –

29

Utilizzare il seguente frammento di aggiungere un interruttore per il layout tramite XML:

<Switch 
    android:id="@+id/on_off_switch" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textOff="OFF" 
    android:textOn="ON"/> 

Poi, nel tuo onCreate di attività metodo, ottenere un riferimento al tuo Switch e impostare il suo OnCheckedChangeListener:

Switch onOffSwitch = (Switch) findViewById(R.id.on_off_switch); 
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 

@Override 
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
    Log.v("Switch State=", ""+isChecked); 
}  

}); 
+3

Questa è una risposta più chiara che ti dà il layout e il codice dietro per abbinare. – AshesToAshes

+0

come gestire più switchcompat nel singolo listener? Si prega di suggerire la risposta per quello –

16

Definire il layout XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.neoecosystem.samplex.SwitchActivity"> 

    <Switch 
     android:id="@+id/myswitch" 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" /> 

</RelativeLayout> 

quindi creare attività

public class SwitchActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener { 

    Switch mySwitch = null; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_switch); 


     mySwitch = (Switch) findViewById(R.id.myswitch); 
     mySwitch.setOnCheckedChangeListener(this); 
    } 

    @Override 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
     if (isChecked) { 
      // do something when check is selected 
     } else { 
      //do something when unchecked 
     } 
    } 

    **** 
} 

======== Per sotto API 14 uso SwitchCompat =========

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.neoecosystem.samplex.SwitchActivity"> 

    <android.support.v7.widget.SwitchCompat 
     android:id="@+id/myswitch" 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" /> 

</RelativeLayout> 

attività

public class SwitchActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener { 

    SwitchCompat mySwitch = null; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_switch); 


     mySwitch = (SwitchCompat) findViewById(R.id.myswitch); 
     mySwitch.setOnCheckedChangeListener(this); 
    } 

    @Override 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
     if (isChecked) { 
      // do something when checked is selected 
     } else { 
      //do something when unchecked 
     } 
    } 
    ***** 
} 
+2

non dimenticare di controllare buttonView.isPressed() – JacksOnF1re

4

Il layout per il widget Switch è simile a questo.

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 
    <Switch 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginRight="20dp" 
     android:gravity="right" 
     android:text="All" 
     android:textStyle="bold" 
     android:textColor="@color/black" 
     android:textSize="20dp" 
     android:id="@+id/list_toggle" /> 
</LinearLayout> 

Nella classe Attività, è possibile codificare in due modi. Dipende dall'uso che puoi codificare.

primo modo

public class ActivityClass extends Activity implements CompoundButton.OnCheckedChangeListener { 
Switch list_toggle; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.return_vehicle); 

    list_toggle=(Switch)findViewById(R.id.list_toggle); 
    list_toggle.setOnCheckedChangeListener(this); 
    } 
} 

public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { 
    if(isChecked) { 
     list_toggle.setText("Only Today's"); //To change the text near to switch 
     Log.d("You are :", "Checked"); 
    } 
    else { 
     list_toggle.setText("All List"); //To change the text near to switch 
     Log.d("You are :", " Not Checked"); 
    } 
} 

Secondo modo

public class ActivityClass extends Activity { 
Switch list_toggle; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.return_vehicle); 

    list_toggle=(Switch)findViewById(R.id.list_toggle); 
    list_toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      if(isChecked) { 
      list_toggle.setText("Only Today's"); //To change the text near to switch 
      Log.d("You are :", "Checked"); 
      } 
      else { 
      list_toggle.setText("All List"); //To change the text near to switch 
      Log.d("You are :", " Not Checked"); 
      } 
     }  
    }); 
    } 
} 
0

Per coloro che utilizzano Kotlin, è possibile impostare un listener per un interruttore (in questo caso con l'ID mySwitch) come segue:

mySwitch.setOnCheckedChangeListener { _, isChecked -> run { 
     // do whatever you need to do when the switch is toggled here 
    } 
} 

isChecked è true se lo switch è attualmente selezionato (ON) e false otherw ISE.

Problemi correlati