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

Ric*_*aad 3 android android-gridview

我想在GridView上实现Radio Group,因此只能在grid的元素中选择单个项目.

请帮忙.

Ric*_*aad 11

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

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>
Run Code Online (Sandbox Code Playgroud)

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;

}
Run Code Online (Sandbox Code Playgroud)