please Click here to see the problematic image
我是android初学者,我需要一些想法来解决我的疑问,我的疑问是当一个开关按钮处于 Activity 状态时,其他两个开关按钮应该保持不活动或禁用状态,我们如何执行此 Activity 有人可以为我提供任何想法...?我当前刚刚插入了开关按钮,我应该如何执行此任务。
我刚刚在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 变量/类属性,这意味着只有最后一个定义实际上可以在您的代码中处理。
不要这样做
btnswitch = (Switch)findViewById(R.id.switch1);
btnswitch = (Switch)findViewById(R.id.switch2);
btnswitch = (Switch)findViewById(R.id.switch3);
相反,为您的 Activity 提供更多类属性来单独处理每个 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
*/
}
}
});
关于java - 我有三个开关按钮,如果一个开关按钮处于 Activity 状态,那么其他两个开关按钮应保持不活动或禁用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51210651/