gpt4 book ai didi

android - Android 中 Grid View 上的 Radio Group 实现

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:29 31 4
gpt4 key购买 nike

我想在 GridView 上实现 Radio Group,以便在网格元素中只能选择单个项目。

请帮忙。

最佳答案

限制从网格中选择元素的目的可以实现如下:

1.网格元素的创建。

<LinearLayout
android:id="@+id/item_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />

<RadioButton
android:id="@+id/radiobtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Image" />


</LinearLayout>

2.在自定义适配器的getView()方法中扩充此xml。

public class MyAdapter extends BaseAdapter {

Context mCtx;
int[] mImg;
LayoutInflater layoutInflater;
RadioGroup rgp;
private RadioButton mSelectedRB;
private int mSelectedPosition = -1;

public MyAdapter(Context context, int[] img) {
this.mCtx = context;
this.mImg = img;
rgp = new RadioGroup(context);
layoutInflater = (LayoutInflater) mCtx
.getSystemService(LAYOUT_INFLATER_SERVICE);

}

@Override
public int getCount() {

return mImg.length;
}

@Override
public Object getItem(int position) {

return null;
}

@Override
public long getItemId(int position) {

return 0;
}

@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View view = convertView;
Holder holder;

if (view == null) {
view = layoutInflater.inflate(R.layout.element, null);
holder = new Holder();
holder.image = (ImageView) view.findViewById(R.id.imageView);
holder.radioButton = (RadioButton) view
.findViewById(R.id.radiobtn);
view.setTag(holder);

} else {

holder = (Holder) view.getTag();
}

holder.radioButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

if ((position != mSelectedPosition && mSelectedRB != null)) {
mSelectedRB.setChecked(false);
}

mSelectedPosition = position;
mSelectedRB = (RadioButton) v;
}
});

if (mSelectedPosition != position) {
holder.radioButton.setChecked(false);
} else {
holder.radioButton.setChecked(true);
if (mSelectedRB != null && holder.radioButton != mSelectedRB) {
mSelectedRB = holder.radioButton;
}
}

return view;
}

}

private class Holder {

ImageView image;
RadioButton radioButton;

}

关于android - Android 中 Grid View 上的 Radio Group 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12781830/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com