我正在制作一个可以打开和关闭的应用程序。我总共有4个开关,在底部,我想有一个按钮可以同时将它们全部关闭-就像一个超驰开关。我正在尝试遵循与创建4个开关时相同的格式,但是我无法确定会怎样。我已经尝试通过stackOverFlow查看,但是找不到任何内容,也许我只是不知道关键字。

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

最佳答案

我总共有4个开关,在底部,我想有一个按钮可以同时将它们全部关闭-就像一个超驰开关。


如果我了解问题,您将遇到以下问题:

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


请记住,将您的Switch声明为字段类变量,以便在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);
        ....

    }

关于android - Android“切换所有按钮”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29881619/

10-11 22:51
查看更多