Android网格视图保持项目选定

19

我有一个包含多个项的GridView,但是当调用onClick监听器后,这些项必须保持选中状态。如何实现?

我已经尝试过v.setSelected(true),但似乎没有效果。

gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            // Toast.makeText(Project.this, "Red" + position,
            // Toast.LENGTH_SHORT).show(); //position = al catelea element
            v.setPressed(true);
            if (bp == 2) {
                if (position == 0) {
                Square.setSex(R.drawable.girl_body2v);
                Square2.setHair(R.drawable.girl_hair_01v);
                SquareAccesories.setAcc(R.drawable.girl_accessories_01v);
                SquareEyes.setEyes(R.drawable.eyes_1v);
                SquareLips.setLips(R.drawable.lip_1v);
                Square3.setDress(R.drawable.girl_tops_01v);
                SquareShoes.setShoes(R.drawable.girl_shoes_01v);
                SquarePants.setPants(R.drawable.girl_bottom_01v);
                setS(2);

这是onClickListener代码的一小部分,因为我有很多情况需要处理。


你能提供一些代码吗? - DroidBender
6个回答

52

我认为更好的方法是告诉GridView,你希望支持选择(勾选)项目:

gridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE);

确保在 GridView 中的项目实现了Checkable接口。这意味着项目可以是Checkbox, ToggleButton 等,或者您可以自己添加Checkable支持 - 例如,使RelativeLayout可选。 (请参见下面的示例。)

与其他答案相比,大部分工作由GridView本身完成 - 不需要onClickListener。不要存储状态,只需调用gridView.getCheckedItemIds()或类似方法。


要使RelativeLayout(或任何内容)可选,请创建其子类:

public class CheckableRelativeLayout extends RelativeLayout implements Checkable {
    private boolean checked = false;
    private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };

    public CheckableRelativeLayout(Context context) {
        super(context);
    }

    public CheckableRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CheckableRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
         final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
         if (isChecked())
             mergeDrawableStates(drawableState, CHECKED_STATE_SET);
         return drawableState;
    }

    @Override
    public boolean isChecked() {
        return checked;
    }

    @Override
    public void setChecked(boolean _checked) {
        checked = _checked;
        refreshDrawableState();
    }

    @Override
    public void toggle() {
        setChecked(!checked);
    }

}

请注意,方法 onCreateDrawableState 更新视觉样式。你不一定非得这么做,例如你可以在 setChange 方法中直接更改背景。

然后将 CheckableRelativeLayout 用作 GridView 中每个项的顶部视图:

<foo.bar.CheckableRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/my_awesome_background"
    ... more stuff
    >
        ...  content of the relative layout
</com.test.CheckableRelativeLayout>

定义当项目在 res/drawable/my_awesome_background.xml 中被选中时,背景如何更改:

<selector xmlns:android="http://schemas.android.com/apk/res/android" > 
     <item android:state_checked="true" >
        <!-- This applies when the item is checked. -->
         <shape android:shape="rectangle"  >
             <solid android:color="#A8DFF4" />
         </shape>
     </item>

    <item>
        <!-- This applies when the item is not checked. -->
        <shape android:shape="rectangle"  >
             <solid android:color="#EFEFEF" />
         </shape>
     </item>
</selector>

你会如何将你的代码应用到包含图片的GridView中? - Andrei Drynov
无法与StickyHeadersGridView一起使用...但这是一个很棒的库,值得手动完成。但这是最佳实践 =) - Renan Franca
只需将OnCLickListener添加到其中并检查它是否选中/取消选中。 - Strix
请注意,如果您不需要重复使用此代码,则可以在getView内创建一个匿名类,并覆盖onCreateDrawableState,但是请将其中的isChecked()替换为((AbsListView)parent).isItemChecked(position) - Dax Fohl
2
当滚动GridView时,视图会被销毁并重新创建,因此这种方法行不通... 当网格被滚动时,先前选择的项目可能会被销毁/回收,并且检查将出现在此网格的意外子视图中。 在我的情况下,在Android 2.3.3上我看到了这种情况。 - Kurovsky
显示剩余4条评论

19

您想要实现的概念是可行的,但不像您现在的工作方式那样。

最好、最简单的解决方案是跟踪已点击项的状态并在适配器内为它们提供正确的布局。我设置了一个小例子:

活动

public class StackOverFlowActivity extends Activity {
    GridView gridView;
    MyCustomAdapter myAdapter;
    ArrayList<GridObject> myObjects;

    static final String[] numbers = new String[] { "A", "B", "C", "D", "E",
            "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z" };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myObjects = new ArrayList<GridObject>();
        for (String s : numbers) {
            myObjects.add(new GridObject(s, 0));
        }

        gridView = (GridView) findViewById(R.id.gridView1);

        myAdapter = new MyCustomAdapter(this);

        gridView.setAdapter(myAdapter);
        gridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
                myObjects.get(position).setState(1);
                myAdapter.notifyDataSetChanged();
            }
        });
    }

    static class ViewHolder {
        TextView text;
    }

    private class MyCustomAdapter extends BaseAdapter  {

        private LayoutInflater mInflater;

        public MyCustomAdapter(Context context) {
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            GridObject object = myObjects.get(position);
            ViewHolder holder;

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.text);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.text.setText(object.getName());

            if (object.getState() == 1) {
                holder.text.setBackgroundColor(Color.GREEN);
            } else {
                holder.text.setBackgroundColor(Color.BLUE);
            }
            return convertView;
        }

        @Override
        public int getCount() {
            return myObjects.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
    }
}

GridObject

public class GridObject {

    private String name;
    private int state;

    public GridObject(String name, int state) {
        super();
        this.name = name;
        this.state = state;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }   
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <GridView
        android:id="@+id/gridView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="50dp"
        android:gravity="center"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth" >
    </GridView>

</LinearLayout>

list_item_icon_text

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

4
在业务(模型)类中存储checked状态是一个不好的想法。应该由显示数据的视图来处理它。此外,在适配器和onClickListener中切换背景看起来像是一种hack。GridView可以为您完成大部分工作,为什么不让它自己做?(请查看我的回答。) - Strix
2
但是这种方法只适用于滚动的网格/列表视图,而在视图中存储选中状态则不行,因为在Android中,网格内的视图在滚动时会被回收利用。 - Kurovsky

6
这里是 Strix 的回答的简洁版本(我认为比被接受的回答更好),当你不需要在其他地方重复使用该代码时。你可以在 Adapter.getView 方法中创建一个匿名类,覆盖 onCreateDrawableState,就像 Strix 的回答中一样,但将 isChecked() 替换为 ((AbsListView)parent).isItemChecked(position)。以下是我的适配器中完整的代码,用于在画廊中绘制已选缩略图周围的边框:
public class ImageAdapter extends BaseAdapter {
    private final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };
    public int getCount() {return images.size();}
    public Object getItem(int position) {return images.get(position);}
    public long getItemId(int position) {return position;}

    public View getView(final int position, final View convertView, final ViewGroup parent) {
        final ImageView imageView = new ImageView(getApplicationContext()) {
            @Override public int[] onCreateDrawableState(int extraSpace) {
                final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
                if (((AbsListView)parent).isItemChecked(position)) {
                    mergeDrawableStates(drawableState, CHECKED_STATE_SET);
                }
                return drawableState;
            }
        };
        imageView.setBackground(getResources().getDrawable(R.drawable.my_awesome_background));
        imageView.setScaleType(ImageView.ScaleType.CENTER);
        final byte[] buffer = images.get(position);
        final Bitmap bmp = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
        imageView.setImageBitmap(bmp);
        return imageView;
    }
}

5
在您的适配器类中添加一个包含所选项目位置的变量。
public class GridImageAdapter extends BaseAdapter {
       public int selectedImage = 0;

在适配器的GetView方法中,将所有图像的透明度设置为除所选之外的其他所有图像。
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
    int[] images = { R.drawable.walk, R.drawable.run, R.drawable.jump }

    ImageView imageView = new ImageView(mContext);
    if (position < imgMapper.length) {

        imageView.setImageResource(images[position]);

        if (position != selectedImage) {
            imageView.setImageAlpha(50);
        }
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
    };

    return imageView;
}

在主方法中的点击处理程序中,保存所选项目的位置。通知适配器已更改。
   myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            GridImageAdapter myAdapter = (GridImageAdapter) myGridView.getAdapter();
            myAdapter.selectedImage = position;
            myAdapter.notifyDataSetChanged();
        }
    });

此外,您还可以使用所选图像执行许多其他操作,例如,如果您想要着色它,只需使用:imageView.setBackgroundColor(Color.BLUE); - maniac
+1 很好的方法,简单而美妙!然而,我更喜欢在适配器内部直接更改selectedImage并通知更改,但更重要的是,我选择在第一次调用getView时创建imageview并重用它来显示其他图片(作为ViewHolder模式)。优点是适配器不需要为每个项目创建多个视图。这与您的答案非常匹配。 - Blo

1

GridView中的视图必须是CheckBoxs,这样您就可以选中和取消选中它们。


我该如何在GridView中添加复选框? - ChanChow
请查看http://www.youtube.com/watch?v=wDBM6wVEO70以开始。ListView和GridView的工作方式相同。 - Strix

0
**You can add tag and check for tag**


 gv.setOnItemClickListener((adapterView, view, i, l) -> {

                int f = gv.getCheckedItemPosition();

                if(view.getTag()=="selected")
                {
                    view.setTag("notselected");
                    String clickedText = gv.getItemAtPosition(i).toString();
                    filterKeywords.remove(clickedText);
                    view.setBackgroundColor(Color.WHITE);
                }
                else
                {
                    view.setTag("selected");
                    String clickedText = gv.getItemAtPosition(i).toString();
                    filterKeywords.add(clickedText);
                    view.setBackgroundColor(Color.GREEN);

                }

                System.out.println("KEYWORDS"+filterKeywords);


            });

1
你可能会喜欢如何在Java中比较字符串? - Dima Kozhevin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接