2011-06-13 148 views
5

我想創建一個包含RadioGroup的自定義View。在RadioGroup內部,我想要設置RadioButtons,以便第一個RadioButton位於左上方,第二個位於下方,第一個位於右側第三位,下方位於第四位。換句話說,我想創建一個組,其中的單選按鈕排列在一個正方形中。我認爲如果我將組的方向設置爲垂直,那麼所有的單選按鈕都將處於一條直線上。另一方面,如果我將方向設置爲水平方向,那麼再次,這些單選按鈕將全部位於一條直線上,並呈水平狀態。有沒有辦法做我想做的事情,還是我被迫設置了兩個單獨的RadioGroups,都是水平定位?以編程方式設置RadioGroup

+0

您可以使用RelativeLayout而不是LinearLayout – Pratik 2011-06-13 14:53:52

+1

@Pratik會有幫助嗎?這將幫助我建立一個相對於別的東西的組,但是相對於彼此的按鈕又如何呢? – LuxuryMode 2011-06-13 15:03:37

回答

31

嘗試處理RadioButtons而不使用RadioGroup

接通個人RadioButtons並將其保存在ArrayList<RadioButton>中。

List<RadioButton> radioButtons = new ArrayList<RadioButton>(); 

radioButtons.add((RadioButton)findViewById(R.id.button1));   
radioButtons.add((RadioButton)findViewById(R.id.button2)); 
radioButtons.add((RadioButton)findViewById(R.id.button3)); 
etc. 

每個RadioButton設置一個OnCheckedChangeListener

for (RadioButton button : radioButtons){ 

    button.setOnCheckedChangeListener(new OnCheckedChangeListener(){ 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      if (isChecked) processRadioButtonClick(buttonView); 
     } 
    }); 

} 

然後創建一個方法來取消選中未選中的RadioButtons

private void processRadioButtonClick(CompoundButton buttonView){ 

    for (RadioButton button : radioButtons){ 

     if (button != buttonView) button.setChecked(false); 
    } 

} 

使用這種方法,RadioButtons可以位於XML佈局的任何位置。

+0

真棒回答馬特,你能解釋如何獲得選定單選按鈕的ID,我試過但我失敗了。等待您的寶貴答案。謝謝。 – 2017-05-26 06:55:31

0

您應該從RadioGroup繼承並覆蓋onLayout()方法。

+0

謝謝!你有沒有一個例子,說明我想要做的重寫會是什麼樣子? – LuxuryMode 2011-06-13 15:19:39

+0

你可以想出如何從Roman Nurik的儀表板視圖實現onLayout:https://gist.github.com/882650 – woodshy 2011-06-13 15:23:24