Android gridview keep item selected

后端 未结 6 1449
失恋的感觉
失恋的感觉 2020-11-29 06:18

I have a GridView with multiple items, but the items must be kept selected once the the onClickListener is called.How can i achive this?

I\'v already tried v.s

6条回答
  •  被撕碎了的回忆
    2020-11-29 06:55

    Here's a terser version of Strix's answer (which I think is better than the accepted answer) when you don't need to reuse that code elsewhere. Instead of creating a new class and implementing Checked, you can just create an anonymous class inside your Adapter.getView method, overriding onCreateDrawableState as in Strix's answer, but replace isChecked() there with ((AbsListView)parent).isItemChecked(position). Here's the full code from my adapter that draws a border around checked thumbnails in a gallery:

    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;
        }
    }
    

提交回复
热议问题