简体   繁体   English

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

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

please Click here to see the problematic image 请点击这里查看有问题的图片

i am beginner in android I need some idea to solve my doubt and my doubt is when one switch button is active then the other two switch button should remain inactive or disabled how can we perform this activity can someone provide me any ideas...? 我是android的初学者,我需要一些想法来解决我的疑问,我的疑问是,当一个开关按钮处于活动状态时,另外两个开关按钮应保持不活动或禁用状态。我们如何执行此活动?有人可以向我提供任何想法吗? I've just currently inserted the switch buttons how should i perform this task. 我刚刚插入了开关按钮,我应该如何执行此任务。

i just used relative layout in android programming 我只是在android编程中使用相对布局

My sourcecode: 我的源代码:

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

Guide me through this. 通过这个引导我。

First of all, you are assigning three different gui elements (your Switch es) to the same java variable / class attribute of your Activity , that means only the last definition can actually be handled in your code. 首先,您将三个不同的gui元素(您的Switch es)分配给Activity的相同java变量/ class属性,这意味着您的代码中实际上只能处理最后一个定义。

Don't do 不要做

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

instead, provide more class attributes to your activity to handle each Switch separately 相反,请为您的活动提供更多的类属性,以分别处理每个Switch

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

Then add listeners to them (example for the first one only): 然后向其添加侦听器(仅第一个示例):

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