Android "Toggle off all buttons"

Android "Toggle off all buttons"

我正在制作一个可以关闭和打开开关的应用程序。我总共有 4 个开关,在底部我想有一个按钮可以同时关闭它们 - 就像一个覆盖开关。我试图遵循与创建 4 个开关时相同的格式,但我无法理解它会如何。我已经尝试通过 Whosebug 进行查找,但在上面找不到任何内容,也许我只是不知道关键词。

    Switch toggleapp1 = (Switch) findViewById(R.id.app1);
    toggleapp1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                toggleapp1(true);
                Toast.makeText(getApplicationContext(), "[Application1] Enabled!", Toast.LENGTH_LONG).show();
            } else {
                toggleapp1(false);
                Toast.makeText(getApplicationContext(), "[Application1] Disabled!", Toast.LENGTH_LONG).show();
            }
        }
    });

其中一个开关的外观。 toggleapp1 与 2,3,4 切换。

public boolean toggleapp1(boolean status) {
    if (status == true) {
        return true;
    }
    else if (status == false) {
        return false;
    }
    return status;
}

I have 4 switches in total and at the bottom I would like to have a button that will toggle them all off at the same time - like an override switch.

如果我理解你遇到的问题:

toggleapp1 = (Switch) findViewById(R.id.app1);
toggleapp2 = (Switch) findViewById(R.id.app2);
toggleapp3 = (Switch) findViewById(R.id.app3);
toggleapp4 = (Switch) findViewById(R.id.app4);

并且您想一起禁用所有这些。 您可以创建一个方法来执行此操作:

private toggleOffSwitches(boolean state) {
    toggleapp1.setChecked(state);
    toggleapp2.setChecked(state);
    toggleapp3.setChecked(state);
    toggleapp4.setChecked(state);
}

并在按钮的OnClickListener中调用:

Button yourButton = (Button) findViewById(R.id.yourButton);
yourButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        toggleOffSwitches(false);
    }
});

请记住将您的开关声明为字段 class 变量,以便在 toggleOffSwitches 方法中使用它们!

更新

例如:

public class MainActivity extends Activity {

    private Switch toggleapp1;

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

        ....
        toggleapp1 = (Switch) findViewById(R.id.app1);
        ....

    }