簡體   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