android.widget.Switch - on/off event listener?

前端 未结 11 1497
庸人自扰
庸人自扰 2020-12-02 04:56

I would like to implement a switch button, android.widget.Switch (available from API v.14).



        
11条回答
  •  [愿得一人]
    2020-12-02 05:29

    The layout for Switch widget is something like this.

    
        
    
    

    In the Activity class, you can code by two ways. Depends on the use you can code.

    First Way

    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");
        }
    }
    

    Second way

    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");
              }
           }       
         });
       }
    }
    

提交回复
热议问题