2011-03-17 47 views
2

如何使一個列表對話框,像這樣的行:Android:如何使AlertDialog具有2個文本行和RadioButton(單選)?

|-----------------------------| 
| FIRST LINE OF TEXT  (o) | <- this is a "RadioButton" 
| second line of text   | 
|-----------------------------| 

我知道我應該使用自定義適配器,通過一個排佈置人士的意見(實際上,我做了這一點)。但單擊該行時,RadioButton不會被選中。

對話是否可以管理它自己的單選按鈕?

回答

2

我找到了解決方案herehere

基本上,我們必須創建一個「Checkable」佈局,因爲視圖的根項目必須實現Checkable接口。

所以我創建了一個可以掃描RadioButton和voilá的RelativeLayout包裝器,這個魔法已經完成了。

public class CheckableLayout extends RelativeLayout implements Checkable 
{ 
    private RadioButton _checkbox; 

    public CheckableLayout(Context context, AttributeSet attrs) 
    { 
     super(context, attrs); 
    } 

    @Override 
    protected void onFinishInflate() 
    { 
     super.onFinishInflate(); 
     // find checkable view 
     int childCount = getChildCount(); 
     for (int i = 0; i < childCount; ++i) 
     { 
      View v = getChildAt(i); 
      if (v instanceof RadioButton) 
      { 
       _checkbox = (RadioButton) v; 
      } 
     } 
    } 

    public boolean isChecked() 
    { 
     return _checkbox != null ? _checkbox.isChecked() : false; 
    } 

    public void setChecked(boolean checked) 
    { 
     if (_checkbox != null) 
     { 
      _checkbox.setChecked(checked); 
     } 
    } 

    public void toggle() 
    { 
     if (_checkbox != null) 
     { 
      _checkbox.toggle(); 
     } 
    } 

} 

你可以用複選框或任何你需要的。

+0

不錯。如果您使用[CompoundButton](http://developer.android.com/reference/android/widget/CompoundButton.html)而不是RadioButton,則它將像複選框或切換按鈕一樣工作。 – dgmltn 2011-04-05 17:39:02

相關問題