繁体   English   中英

我有三个开关按钮,如果一个开关按钮处于活动状态,则其他两个开关按钮应保持不活动或禁用

[英]I have three switch button, if one switch button is active then other two switch button should remain inactive or disable

请点击这里查看有问题的图片

我是android的初学者,我需要一些想法来解决我的疑问,我的疑问是,当一个开关按钮处于活动状态时,另外两个开关按钮应保持不活动或禁用状态。我们如何执行此活动?有人可以向我提供任何想法吗? 我刚刚插入了开关按钮,我应该如何执行此任务。

我只是在android编程中使用相对布局

我的源代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    button=(Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            openThird();
        }
    });
    btnswitch=(Switch)findViewById(R.id.switch1);
    btnswitch=(Switch)findViewById(R.id.switch2);
    btnswitch=(Switch)findViewById(R.id.switch3);
}
public void openThird()
{
    Intent toy=new Intent(this,Third.class);
    startActivity(toy);
}   

通过这个引导我。

首先,您将三个不同的gui元素(您的Switch es)分配给Activity的相同java变量/ class属性,这意味着您的代码中实际上只能处理最后一个定义。

不要做

btnswitch = (Switch)findViewById(R.id.switch1);
btnswitch = (Switch)findViewById(R.id.switch2);
btnswitch = (Switch)findViewById(R.id.switch3);

相反,请为您的活动提供更多的类属性,以分别处理每个Switch

btnswitchOne = (Switch)findViewById(R.id.switch1);
btnswitchTwo = (Switch)findViewById(R.id.switch2);
btnswitchThree = (Switch)findViewById(R.id.switch3);

然后向其添加侦听器(仅第一个示例):

btnSwitchOne.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // do your desired action on switch on/off
        if (isChecked) {
            // if the first switch gets checked, uncheck the others
            btnSwitchTwo.setChecked(false);
            btnSwitchThree.setChecked(false);
        } else {
            /* since you are switching them off by code depending on other's state,
             * either skip the else-block entirely or print some debug messages
             */
        }
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM