2013-03-05 58 views
1

我想在GridView中放置幾十個單選按鈕。 現在,我已經通過創建一個自定義適配器並重寫getView函數(然後在GridView上調用setAdapter)來實現此目的。 唯一的問題是,我無法在RadioGroup中插入這些單選按鈕,因此我可以強制單個按鈕的選擇。Android:在GridView中使用RadioGroup

我已經看過各種計算器的帖子(比如這個:Radio Group implementation on Grid View in Android),但我還沒有找到一個簡單的方法來完成這件事。我曾嘗試在我的主XML中的GridView標記周圍放入RadioGroup標記,但那沒有奏效。

下面是我的一些相關的代碼至今:

private class RadioGridAdapter extends BaseAdapter{ 
    private Context mContext; 
    RadioGridAdapter(Context c) { 
     mContext = c; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent){ 
     LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     View gridView; 
     if(convertView == null) { 
      gridView = inflater.inflate(R.layout.cell, null); 

      //set value into Button 
      RadioButton ButtonView = (RadioButton) gridView.findViewById(R.id.interval_button); 
      ButtonView.setText(intervals[position]); 

     } else { 
      gridView = (View) convertView; 
     } 

     return gridView; 
    } 
} 

cell.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 
<RadioButton 
    android:id="@+id/interval_button" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 
</RadioButton> 
</LinearLayout> 

activity_main.xml中:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
tools:context=".MainActivity" > 

<GridView 
    android:id="@+id/gridview" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:columnWidth="90dp" 
    android:gravity="center" 
    android:horizontalSpacing="20dp" 
    android:numColumns="auto_fit" 
    android:paddingLeft="15sp" 
    android:paddingRight="15sp" 
    android:stretchMode="columnWidth" 
    android:verticalSpacing="10dp" > 
</GridView> 

</LinearLayout> 

謝謝!

UPDATE: 根據這個帖子(radio button multiple rows)以及這個職位(How to group a 3x3 grid of radio buttons?),沒有這樣做,但不擴展RadioGroup中類的簡單的方法自己有一個網格格式包裝單選按鈕的能力..有誰知道這種使用RaioGroup的開源項目嗎?

回答

0

您可以使用ListView而不是GridView。 enter image description here

如需幫助,請參閱我的Android應用程序博客中

http://amitandroid.blogspot.in/2013/03/android-listview-with-radiogroup.html

希望這個博客將幫助你很多。

非常感謝,

+0

感謝您的迴應。 這是否會讓所有這些單選按鈕都在一個RadioGroup中?如果是這樣,你能詳細說明你是如何得到這個的? – alphaJA 2013-03-05 06:04:25

+0

你可以參考我以後發佈的鏈接。 在該鏈接(Android博客)中,我編寫了步驟以及在底部發布了完整的源代碼。 – 2013-03-05 06:23:47

+0

我試着運行源代碼,但Eclipse告訴我「無法解析目標」Google Inc.:Google APIs:8'「......我猜測我們的開發環境太不同了?我仍然是Eclipse/Android編程的新手,所以我不確定它爲什麼不起作用。 另外,它看起來像你在這裏有一個RadioGroup每行,但我想有一個RadioGroup整個網格。這仍然有可能與ListView? – alphaJA 2013-03-05 15:42:24