2017-01-02 33 views
0

上週我剛開始學習,我對我的書上的RadioGroup有一些疑問。RadioGroup and checkedId


radioGroup.clearCheck(); 

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(RadioGroup group, int checkedId) { 
      RadioButton rb = (RadioButton) group.findViewById(checkedId); 

       switch (rb.getId()) { 

        case R.id.radioButtonLondon: 
         tClock.setTimeZone("Europe/London"); 
         break; 

        case R.id.radioButtonBeijing: 
         tClock.setTimeZone("CST6CDT"); 
         break; 


        case R.id.radioButtonNewYork: 
         tClock.setTimeZone("America/New_York"); 
         break; 
       } 
       // End switch block 

      //} 
     } 
    }); 

  1. 我那本書,它說RadioButton rb = (RadioButton) group.findViewById(checkedId);用於

「得到一個參考實際的對象checkedId指的是, 那麼我們就可以檢索我們用於當前 所選單選按鈕的熟悉ID,爲此我們現在使用存儲在 rb中的參考文獻「。

我很困惑這個交代

  • 這是行RadioButton rb = (RadioButton) group.findViewById(checkedId);有必要嗎?我試圖隱藏這條線,並將switch (rb.getId())更改爲switch(checkedId),一切仍然正常。
  • 謝謝!

    +0

    你不需要這條線..RadioButton rb =(RadioButton)group.findViewById(checkedId); – rafsanahmad007

    +1

    看到這個https://developer.android.com/reference/android/widget/RadioGroup.OnCheckedChangeListener.html – rafsanahmad007

    回答

    0

    不要定義radiobutton.In setOnCheckedChangeListener本身,你會得到的單選按鈕id.Remove RadioButton rb = (RadioButton) group.findViewById(checkedId);

    您的代碼應該是這樣的:

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
        @Override 
        public void onCheckedChanged(RadioGroup group, int checkedId) { 
    
          switch (checkedId) { 
    
           case R.id.radioButtonLondon: 
            tClock.setTimeZone("Europe/London"); 
            break; 
    
           case R.id.radioButtonBeijing: 
            tClock.setTimeZone("CST6CDT"); 
            break; 
    
    
           case R.id.radioButtonNewYork: 
            tClock.setTimeZone("America/New_York"); 
            break; 
          } 
          // End switch block 
    
         //} 
        } 
    }); 
    
    0

    眼看你只更新「TCLOCK 「那麼你說得對那條線沒有必要。如果出於某種其他原因,您需要調用任何可用的單選按鈕方法。