Android How do I correctly get the value from a Switch?

前端 未结 5 1271
醉酒成梦
醉酒成梦 2020-12-07 22:02

I\'m creating a Android application which uses a Switch.
I\'m trying to listen for changes and get the value when changed.
I have two questions when usi

相关标签:
5条回答
  • 2020-12-07 22:42
    Switch s = (Switch) findViewById(R.id.SwitchID);
    
    if (s != null) {
        s.setOnCheckedChangeListener(this);
    }
    
    /* ... */
    
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        Toast.makeText(this, "The Switch is " + (isChecked ? "on" : "off"),
                       Toast.LENGTH_SHORT).show();
        if(isChecked) {
            //do stuff when Switch is ON
        } else {
            //do stuff when Switch if OFF
        }
    }
    

    Hint: isChecked is the new switch value [true or false] not the old one.

    0 讨论(0)
  • 2020-12-07 22:48

    Kotlin but in More readable Java Style

       videoLoopSwitch.setOnCheckedChangeListener(object : CompoundButton.OnCheckedChangeListener{
                    override fun onCheckedChanged(switch: CompoundButton?, isChecked: Boolean) {
                        videoPlayer?.apply {
                            setLooping(isChecked)
                        }
                    }
                })
    
    0 讨论(0)
  • 2020-12-07 22:51

    I added this in kotlin

    switchImage.setOnCheckedChangeListener { compoundButton: CompoundButton, b: Boolean ->
        if (b) // Do something
        else // Do something
    }
    
    0 讨论(0)
  • 2020-12-07 22:56
    Switch switch = (Switch) findViewById(R.id.Switch2);
    
    switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            ...switch on..
                        } else {
                           ...switch off..
                        }
                    }
                });
    

    i hope this will solve your problem

    0 讨论(0)
  • 2020-12-07 23:05

    Since it extends from CompoundButton (docs), you can use setOnCheckedChangeListener() to listen for changes; use isChecked() to get the current state of the button.

    0 讨论(0)
提交回复
热议问题