【发布时间】:2013-02-19 06:47:05
【问题描述】:
我想在 GridView 中布置几十个单选按钮。 现在,我通过创建自定义适配器并覆盖 getView 函数(然后在 GridView 上调用 setAdapter)来实现这一点。 唯一的问题是,我无法将这些单选按钮包含在 RadioGroup 中,因此我可以强制单选按钮。
我查看了各种 stackoverflow 帖子(例如这个: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>
谢谢!
更新: 根据这篇文章(radio button multiple rows)和这篇文章(How to group a 3x3 grid of radio buttons?),如果不扩展 RadioGroup 类以使其能够以网格格式包装单选按钮,则没有一种简单的方法可以做到这一点。有人知道以这种方式使用 RaioGroup 的开源项目吗?
【问题讨论】:
标签: java android gridview adapter radio-group