我想在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的开源项目吗?
感谢您的回应。 这是否会让所有这些单选按钮都在一个RadioGroup中?如果是这样,你能详细说明你是如何得到这个的? – alphaJA 2013-03-05 06:04:25
你可以参考我以后发布的链接。 在该链接(Android博客)中,我编写了步骤以及在底部发布了完整的源代码。 – 2013-03-05 06:23:47
我试着运行源代码,但Eclipse告诉我“无法解析目标”Google Inc.:Google APIs:8'“......我猜测我们的开发环境太不同了?我仍然是Eclipse/Android编程的新手,所以我不确定它为什么不起作用。 另外,它看起来像你在这里有一个RadioGroup每行,但我想有一个RadioGroup整个网格。这仍然有可能与ListView? – alphaJA 2013-03-05 15:42:24