Android 中网格视图上的无线电组实现

2024-01-02

我希望在 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;

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android 中网格视图上的无线电组实现 的相关文章

随机推荐