如何突出的回收站查看所选项目? [英] how to highlight the selected Item of Recycler View?

查看:232
本文介绍了如何突出的回收站查看所选项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个回收站视图从内部存储加载的图像。 我想点击时突出显示所选项目。 我尝试了很多事情,但它不工作。 其实我需要的是,当我点击回收站查看任何项目的项目一定要在我的ArrayList和它也应该得到突出显示,并当我再次点击或者说其取消必须再次趋于正常。 这是我的code:

 公共类图片扩展片段{
    私人列表< imageHolder的>图像列表;
    光标imageCursor;

    RecyclerView recyclerView;
    MyImageAdapter适配器;
    ActionButton clickButton;
    名单<字符串> listofImages;
    名单<整数GT; POS机;
    INT参数:columnIndex;
    StringBuilder的StringBuilder的;
    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,捆绑savedInstanceState){
        查看rootlayout = inflater.inflate(R.layout.image,集装箱,假);
        listofImages =新的ArrayList<字符串>();
        POS =新的ArrayList<整数GT;();
        StringBuilder的=新的StringBuilder();
        ContentResolver的imageResolver = getActivity()getContentResolver()。
        乌里imageUri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        串投影[] = {MediaStore.Images.Thumbnails._ID,MediaStore.Images.Media.TITLE};
        imageCursor = getActivity()managedQuery(imageUri,投影,NULL,NULL,NULL);

        clickButton =(ActionButton)rootlayout.findViewById(R.id.action_button);

        recyclerView =(RecyclerView)rootlayout.findViewById(R.id.recycler_view_image);
        适配器=新MyImageAdapter(getActivity(),getImageList());

        recyclerView.setAdapter(适配器);
        recyclerView.setLayoutManager(新LinearLayoutManager(getActivity()));

        recyclerView.addOnItemTouchListener(新RecyclerTouchListener(getActivity(),recyclerView,新RecyclerTouchListener.ClickListener(){
            @覆盖
            公共无效的onClick(视图中查看,INT位置){
               TextView的电视=(TextView中)view.findViewById(R.id.list_text_all);
                    INT标志= 0;

                    的String []投影= {MediaStore.Images.Media.DATA};
                    imageCursor = getActivity()。managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            投影,
                            空值,
                            空值,
                            空值);
                    参数:columnIndex = imageCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    imageCursor.moveToPosition(位置);
                    //获取图像文件名
                    字符串的ImagePath = imageCursor.getString(参数:columnIndex);
                    如果(listofImages.contains(的ImagePath)){
                        Log.d(包含测试,是);
                        listofImages.remove(的ImagePath);
                        pos.remove(位置);
                    } 其他 {
                        listofImages.add(的ImagePath);
                        pos.add(位置);
                        Log.d(包含测试,否);
                    }

                字符串s = listofImages.size()++的ImagePath;
                Log.d(插入,S);
            }

            @覆盖
            公共无效onLongClick(查看视图,INT位置){}
        }));

        clickButton.setOnClickListener(新View.OnClickListener(){
            @覆盖
            公共无效的onClick(视图v){
                的for(int i = 0; I< listofImages.size();我++){
                    stringBuilder.append(listofImages.get(ⅰ)+\ñ);
                }
                Toast.makeText(getActivity(),StringBuilder的,Toast.LENGTH_LONG).show();
            }
        });

        返回rootlayout;
    }

    公开名单< imageHolder的> getImageList(){
        图像列表=新的ArrayList< imageHolder的>();

        如果(imageCursor =空&安培;!&安培; imageCursor.moveToFirst()){

           INT titleColumn = imageCursor.getColumnIndex
                    (android.provider.MediaStore.Images.Media.TITLE);
            INT idColumn = imageCursor.getColumnIndex
                    (android.provider.MediaStore.Images.Media._ID);

            做 {
                imageHolder的IMG =新imageHolder的();
                img.id = imageCursor.getLong(idColumn);
                img.title = imageCursor.getString(titleColumn);

                img.iconid = imageCursor.getInt(idColumn);


                imageList.add(IMG);
            }
            而(imageCursor.moveToNext());
        }

        返回图像列表;
    }
}
 

这是我的适配器类:

 公共类MyImageAdapter扩展RecyclerView.Adapter< MyImageAdapter.MyViewHolder> {
    上下文语境;
    私人LayoutInflater充气;
    名单< imageHolder的>数据= Collections.emptyList();
    私人ClickListener clickListener;
    INT宽度,高度;

    公共MyImageAdapter(上下文的背景下,名单,其中,imageHolder的>数据1){
        充气= LayoutInflater.from(上下文);
        this.data = DATA1;
        this.context =背景;
    }

    @覆盖
    公共MyViewHolder onCreateViewHolder(ViewGroup中的父母,INT viewType){
        查看查看= inflater.inflate(R.layout.all_row,父母,假);
        MyViewHolder持有人=新MyViewHolder(视图);
        回报持有人;
    }

    @覆盖
    公共无效onBindViewHolder(MyViewHolder持有人,INT位置){
        尝试{
            imageHolder的电流= data.get(位置);
            holder.title.setText(current.title);

            Log.d(Imageid:​​+ current.iconid,);
            乌里IMAGE_URI = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,+ current.iconid);

            点阵位图= Bitmap.createScaledBitmap(德codeURI(IMAGE_URI),200,200,真正的);
            holder.img.setImageBitmap(位);
        }
        赶上(例外五){}
    }
    公共无效deleteRecyclerData(INT位置){
        data.remove(位置);
        notifyItemRemoved(位置);
    }


    私人位图德codeURI(URI selectedImage)抛出FileNotFoundException异常{
        BitmapFactory.Options O =新BitmapFactory.Options();
        o.inJustDe codeBounds = TRUE;
        BitmapFactory.de codeStream(
               。context.getContentResolver()openInputStream(selectedImage),空,O);

        最终诠释REQUIRED_SIZE = 100;

        INT width_tmp = o.outWidth,height_tmp = o.outHeight;
        int标= 1;
        而(真){
            如果(width_tmp / 2'; REQUIRED_SIZE || height_tmp / 2'; REQUIRED_SIZE){
                打破;
            }
            width_tmp / = 2;
            height_tmp / = 2;
            规模* = 2;
        }

        BitmapFactory.Options O2 =新BitmapFactory.Options();
        o2.inSampleSize =规模;
        返回BitmapFactory.de codeStream(
                context.getContentResolver()openInputStream(selectedImage),空,O2)。
    }
    @覆盖
    公众诠释getItemCount(){
        返回data.size();
    }

    公共类MyViewHolder扩展RecyclerView.ViewHolder实现View.OnClickListener {
        TextView的称号;
      // TextView的艺术家;
        ImageView的IMG;
        复选框复选框;

        公共MyViewHolder(查看ItemView控件){
            超(ItemView控件);
            标题=(TextView中)itemView.findViewById(R.id.list_text_all);
            IMG =(ImageView的)itemView.findViewById(R.id.list_image_all);
            img.setOnClickListener(本);
        }

        @覆盖
        公共无效的onClick(视图v){}
    }
    公共接口ClickListener {
        公共无效itemClicked(查看视图,INT位置);
    }
}
 

解决方案

您可以使用<一个href="http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList">StateListDrawable以达到预期的效果。

示例

创建一个新的绘制资源文件的在绘制,其内容如下目录:

selector_row.xml

 &LT; XML版本=1.0编码=UTF-8&GT?;
&LT;选择的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android&GT;
    &所述;! - 当选择行颜色 - &GT;
    &LT;项目机器人:可绘制=@机器人:彩色/ darker_gray机器人:STATE_ pressed =假的Andr​​oid版本:state_selected =真/&GT;
    &LT;! - 标准的背景颜色 - &GT;
    &LT;项目机器人:可绘制=@机器人:彩色/白机器人:state_selected =FALSE/&GT;
&LT; /选择器&GT;
 

现在只需使用该<​​code> StateListDrawable 中的行布局背景的 RecyclerView

row_recyclerview.xml

 &LT; RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =WRAP_CONTENT
    机器人:背景=@可绘制/ selector_row&GT;

    &LT;  - !行的内容 - &GT;

&LT; / RelativeLayout的&GT;
 

现在只要在您的适配器的onClick()方法被调用时,你只需要做到以下几点:

  // myBackground是你行的RelativeLayout的根
myBackground.setSelected(真正的);
 

该行的背景将有颜色(在本例中的 darker_gray 的),只要您拨打 myBackground.setSelected(假)。当然,你应该创建一个<一个href="http://developer.android.com/reference/android/util/SparseBooleanArray.html">SparseBooleanArray例如,为了知道选择哪个行和未自的行会被滚动时重复使用。

编辑:记住所选的项目
背后的想法的 SparseBooleanArray 的是要记住这些选择的项目。下面就如何使用它的例子:

 公共类MyImageAdapter扩展RecyclerView.Adapter&LT; MyImageAdapter.MyViewHolder&GT; {

    私人SparseBooleanArray selectedItems;

    // 其他的东西 [...]

    @覆盖
    公共无效onBindViewHolder(MyViewHolder持有人,INT位置){
        //设置该行根据位置的选择状态
        holder.myBackground.setSelected(selectedItems.get(位置,FALSE));
    }

    公共类MyViewHolder扩展RecyclerView.ViewHolder实现View.OnClickListener {

        @覆盖
        公共无效的onClick(视图v){
              //保存选定位置的SparseBooleanArray
              如果(selectedItems.get(getAdapterPosition(),FALSE)){
                  selectedItems.delete(POS);
                  myBackground.setSelected(假);
              }
              其他 {
                  selectedItems.put(getAdapterPosition(),TRUE);
                  myBackground.setSelected(真正的);
              }
        }
    }
}
 

I have a Recycler View with the Images loaded from the Internal Storage. I want to Highlight the selected item when clicked. I tried a lot of thing but it was not working. Actually what I need is when I click any item in Recycler View that Item must go in My ArrayList and it should also get highlighted and again when I click or say unselect it must again become normal. Here is my Code:

public class Images extends Fragment {
    private List<ImageHolder> imageList;
    Cursor imageCursor;

    RecyclerView recyclerView;
    MyImageAdapter adapter;
    ActionButton clickButton;
    List<String> listofImages;
    List<Integer> pos;
    int columnIndex;
    StringBuilder stringBuilder;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,   Bundle savedInstanceState) {
        View rootlayout = inflater.inflate(R.layout.image, container, false);
        listofImages=new ArrayList<String>();
        pos=new ArrayList<Integer>();
        stringBuilder=new StringBuilder();
        ContentResolver imageResolver = getActivity().getContentResolver();
        Uri imageUri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String projection[]={MediaStore.Images.Thumbnails._ID,MediaStore.Images.Media.TITLE};
        imageCursor = getActivity().managedQuery(imageUri, projection, null, null, null);

        clickButton= (ActionButton) rootlayout.findViewById(R.id.action_button);

        recyclerView = (RecyclerView) rootlayout.findViewById(R.id.recycler_view_image);
        adapter = new MyImageAdapter(getActivity(), getImageList());

        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(),recyclerView,new RecyclerTouchListener.ClickListener() {
            @Override
            public void onClick(View view, int position) {
               TextView tv= (TextView) view.findViewById(R.id.list_text_all);
                    int flag=0;

                    String[] projection = {MediaStore.Images.Media.DATA};
                    imageCursor = getActivity().managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            projection, 
                            null,       
                            null,
                            null);
                    columnIndex = imageCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    imageCursor.moveToPosition(position);
                    // Get image filename
                    String imagePath = imageCursor.getString(columnIndex);
                    if (listofImages.contains(imagePath)){
                        Log.d("Contains Test","Yes");
                        listofImages.remove(imagePath);
                        pos.remove(position);
                    } else {
                        listofImages.add(imagePath);
                        pos.add(position);
                        Log.d("Contains Test","No");
                    }

                String s=listofImages.size()+" "+imagePath;
                Log.d("Inserted",s);
            }

            @Override
            public void onLongClick(View view, int position) {}
        }));

        clickButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i=0;i<listofImages.size();i++){
                    stringBuilder.append(listofImages.get(i)+"\n");
                }
                Toast.makeText(getActivity(),stringBuilder,Toast.LENGTH_LONG).show();
            }
        });

        return rootlayout;
    }

    public List<ImageHolder> getImageList() {
        imageList=new ArrayList<ImageHolder>();

        if(imageCursor!=null && imageCursor.moveToFirst()){

           int titleColumn = imageCursor.getColumnIndex
                    (android.provider.MediaStore.Images.Media.TITLE);
            int idColumn = imageCursor.getColumnIndex
                    (android.provider.MediaStore.Images.Media._ID);

            do {
                ImageHolder img=new ImageHolder();
                img.id=imageCursor.getLong(idColumn);
                img.title=imageCursor.getString(titleColumn);

                img.iconid= imageCursor.getInt(idColumn);


                imageList.add(img);
            }
            while (imageCursor.moveToNext());
        }

        return  imageList;
    }
}

This is my Adapter Class:

public class MyImageAdapter extends RecyclerView.Adapter<MyImageAdapter.MyViewHolder> {
    Context context;
    private LayoutInflater inflater;
    List<ImageHolder> data= Collections.emptyList();
    private ClickListener clickListener;
    int width,height;

    public MyImageAdapter(Context context, List<ImageHolder> data1) {
        inflater = LayoutInflater.from(context);
        this.data=data1;
        this.context=context;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.all_row, parent, false);
        MyViewHolder holder=new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        try{
            ImageHolder current=data.get(position);
            holder.title.setText(current.title);

            Log.d("Imageid:"+current.iconid,"");
            Uri IMAGE_URI = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + current.iconid);

            Bitmap bitmap = Bitmap.createScaledBitmap(decodeUri(IMAGE_URI), 200, 200, true);
            holder.img.setImageBitmap(bitmap);
        }
        catch(Exception e){}
    }
    public void deleteRecyclerData(int position){
        data.remove(position);
        notifyItemRemoved(position);
    }


    private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(
               context.getContentResolver().openInputStream(selectedImage), null, o);

        final int REQUIRED_SIZE = 100;

        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
                break;
            }
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(
                context.getContentResolver().openInputStream(selectedImage), null, o2);
    }
    @Override
    public int getItemCount() {
        return data.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        TextView title;
      // TextView artist;
        ImageView img;
        CheckBox checkBox;

        public MyViewHolder(View itemView) {
            super(itemView);
            title= (TextView) itemView.findViewById(R.id.list_text_all);
            img= (ImageView) itemView.findViewById(R.id.list_image_all);
            img.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {}
    }
    public interface ClickListener{
        public void itemClicked(View view, int position);
    }
}

解决方案

You can use a StateListDrawable to achieve the desired effect.

Example

Create a new Drawable resource file in your drawable directory with the following content:

selector_row.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Color when the row is selected -->
    <item android:drawable="@android:color/darker_gray" android:state_pressed="false" android:state_selected="true" />
    <!-- Standard background color -->
    <item android:drawable="@android:color/white" android:state_selected="false" />
</selector>

Now simply use this StateListDrawable as the background in the row-layout of your RecyclerView

row_recyclerview.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/selector_row">

    <!-- row content -->

</RelativeLayout>

Now as soon as the onClick() method in your adapter is called you simply need to do the following:

// myBackground is the RelativeLayout root of your row
myBackground.setSelected(true);

The rows' background will have the color (in this case darker_gray) as long as you call myBackground.setSelected(false). Of course you should create a SparseBooleanArray for example in order to know which row is selected and which isn't since the rows will be reused when scrolling.

Edit: Remember selected items
The idea behind the SparseBooleanArray is to remember the items which are selected. Following a sample on how to use it:

public class MyImageAdapter extends RecyclerView.Adapter<MyImageAdapter.MyViewHolder> {

    private SparseBooleanArray selectedItems;

    // Other stuff [...]

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        // Set the selected state of the row depending on the position
        holder.myBackground.setSelected(selectedItems.get(position, false));
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        @Override
        public void onClick(View v) {
              // Save the selected positions to the SparseBooleanArray 
              if (selectedItems.get(getAdapterPosition(), false)) {
                  selectedItems.delete(pos);
                  myBackground.setSelected(false);
              }
              else {
                  selectedItems.put(getAdapterPosition(), true);
                  myBackground.setSelected(true);
              }
        }
    }
}

这篇关于如何突出的回收站查看所选项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆