如何在RecyclerView中实现单一选择?

时间:2016-08-07 22:51:10

标签: android android-recyclerview

我可以在RecyclerView中更改所选项目的属性,但我想删除旧选择的选择。

以下是我创建RecyclerView的方法:

fragmentViewPagerAdapter.addFragmentView((arg1, arg2, arg3) -> {
        View view = arg1.inflate(R.layout.recyclerview_layout, arg2, false);
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        selectDateRecyclerViewAdapter = new SelectDateRecyclerViewAdapter(dayList,this,(v,position) ->
        {
            AppCompatButton appCompatButton = (AppCompatButton)v.findViewById(R.id.selectHourButton);
            AppCompatImageView appCompatImageView = (AppCompatImageView)v.findViewById(R.id.calendarDot);
            highlightButton(appCompatButton,appCompatImageView);
        });
        recyclerView.setHasFixedSize(false);
        recyclerView.addItemDecoration(selectDateRecyclerViewAdapter. new CalendarItemDecoration(10,dayList.size()));
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),4,GridLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(selectDateRecyclerViewAdapter);
        selectDateRecyclerViewAdapter.notifyDataSetChanged();
        return view;
    });

highlightButton方法更改Button等的背景

感谢。

2 个答案:

答案 0 :(得分:0)

您可能需要保留标记以记录选择了哪些按钮,当您选择新项目时,首先清除标记并将其重置为新选定项目的位置。然后notifyDataSetChanged()notifyItemChanged()。完成。

此函数的主要代码可以放在highlightButton方法中。所以最好如果你发布highlightButton代码。

答案 1 :(得分:0)

由于只有一个选择,您可以使用外部变量跟踪所选位置,例如int selectedIndex;

在适配器代码中:

public class ViewHolder extends RecyclerView.ViewHolder {

                View itemView;        
                public ViewHolder(View v) {
                    super(v);
                    itemView = v;
                    v.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            selectedPostion = getAdapterPosition();
                            if( selectedPosition == RecyclerView.NO_POSITION) return;
                            recyclerViewOnItemClickListener.onItemSelect(itemView, getAdapterPosition()); //Custom listener - in turn calls your highlightButton method

                            //call notifyDataSetChanged(); or notifyItemRangeChanged();
                            }
                    });
                }
            }

     @Override
     public void onBindViewHolder(ViewHolder holder, final int position) {

            holder.itemView.setSelected(position == selectedPostion);
     }