I need to make Toggle Switches for Java

时间:2018-03-08 22:09:13

标签: java android switch-statement toggle radio

Hello Guys can someone tell me how i can make a few toggle switches in Java? Specifically two out of three switches that toggle off when one is turned on?

LIKE THIS

1 个答案:

答案 0 :(得分:1)

假设您有swt1swt2

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;

public class MainActivity extends AppCompatActivity {

    private Switch swt1;
    private Switch swt2;

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

        swt1 = (Switch)findViewById(R.id.swt1);
        swt2 = (Switch)findViewById(R.id.swt2);


        swt1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if(b == true)
                    swt2.setChecked(false);
                else
                    swt2.setChecked(true);
            }
        });

        swt2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if(b == true)
                    swt1.setChecked(false);
                else
                    swt1.setChecked(true);
            }
        });
    }
}

您可以根据需要添加任意数量的开关。只需使用switch.setChecked(true)切换开关,然后switch.setChecked(false)切换开关。

请务必提出任何问题!