如何在RecyclerView上正确突出显示所选项目?


146

我正在尝试使用a RecyclerView作为水平ListView。我试图弄清楚如何突出显示所选项目。当我单击其中一项时,将其选中并正确突出显示,但是当我单击另一项时,第二项将与较旧的一起突出显示。

这是我的onClick函数:

@Override
public void onClick(View view) {

    if(selectedListItem!=null){
        Log.d(TAG, "selectedListItem " + getPosition() + " " + item);
        selectedListItem.setBackgroundColor(Color.RED);
    }
    Log.d(TAG, "onClick " + getPosition() + " " + item);
    viewHolderListener.onIndexChanged(getPosition());
    selectedPosition = getPosition();
    view.setBackgroundColor(Color.CYAN); 
    selectedListItem = view;
}

这是onBindViewHolder

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {   
    viewHolder.setItem(fruitsData[position]);
    if(selectedPosition == position)
        viewHolder.itemView.setBackgroundColor(Color.CYAN);    
    else
        viewHolder.itemView.setBackgroundColor(Color.RED);

}

使用可聚焦视图并不是尝试跟踪所选项目的好主意。检查我的答案以获取完整的解决方案
Greg Ennis


回收者视图项目选择:stackoverflow.com/a/38501676/2648035
Alok Omkar,

这是很难跟随,当你没有任何已有的工作,这是因为沿着答案标签坏,并且不指定太多关于什么去哪里。
FirstOne

Answers:


61

我编写了一个基本适配器类,以使用RecyclerView自动处理项目选择。只需从它派生适配器,并使用带有state_selected的可绘制状态列表,就像使用列表视图一样。

在这里有一篇博客文章,但这是代码:

public abstract class TrackSelectionAdapter<VH extends TrackSelectionAdapter.ViewHolder> extends RecyclerView.Adapter<VH> {
    // Start with first item selected
    private int focusedItem = 0;

    @Override
    public void onAttachedToRecyclerView(final RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);

        // Handle key up and key down and attempt to move selection
        recyclerView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                RecyclerView.LayoutManager lm = recyclerView.getLayoutManager();

                // Return false if scrolled to the bounds and allow focus to move off the list
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                        return tryMoveSelection(lm, 1);
                    } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                        return tryMoveSelection(lm, -1);
                    }
                }

                return false;
            }
        });
    }

    private boolean tryMoveSelection(RecyclerView.LayoutManager lm, int direction) {
        int tryFocusItem = focusedItem + direction;

        // If still within valid bounds, move the selection, notify to redraw, and scroll
        if (tryFocusItem >= 0 && tryFocusItem < getItemCount()) {
            notifyItemChanged(focusedItem);
            focusedItem = tryFocusItem;
            notifyItemChanged(focusedItem);
            lm.scrollToPosition(focusedItem);
            return true;
        }

        return false;
    }

    @Override
    public void onBindViewHolder(VH viewHolder, int i) {
        // Set selected state; use a state list drawable to style the view
        viewHolder.itemView.setSelected(focusedItem == i);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(View itemView) {
            super(itemView);

            // Handle item click and set the selection
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Redraw the old selection and the new
                    notifyItemChanged(focusedItem);
                    focusedItem = getLayoutPosition();
                    notifyItemChanged(focusedItem);
                }
            });
        }
    }
} 

mRecyclerView没有在任何地方声明。我们是否应该仅将其作为参数传递给构造函数,然后将其存储在字段中?
Pedro

1
对于那个很抱歉。我的适配器是我的片段的内部类,因此它可以访问“回收者”视图字段。否则,可以将其作为参数传递。甚至更好的是,onRecyclerViewAttached将其处理并存储在那里的成员变量中。
格雷格·恩尼斯

1
好的答案,但是为什么要使用getChildPosition()?还有另一种方法developer.android.com/reference/android/support/v7/widget/...
skyfishjy

抱歉,您是说我只需要导入您的TrackSelectionAdapter课程并在列表中使用它吗?如何“从您的班级派生我的适配器”?请您回答我的问题吗?:我陷这么深stackoverflow.com/questions/29695811/...
克里斯蒂亚诺Colacillo

2
我尝试了一下,发现对NotifyItemChanged()的两个背靠背调用杀死了在较慢的硬件上平滑滚动的任何外观。在棒棒糖更新之前,在消防电视上的表现尤其糟糕
红衫军

157

这是非常简单的方法。

private int selectedPos = RecyclerView.NO_POSITION;在RecyclerView Adapter类中有一个,然后在onBindViewHolder方法下尝试:

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {   
    viewHolder.itemView.setSelected(selectedPos == position);

}

并在您的OnClick事件中进行修改:

@Override
public void onClick(View view) {
     notifyItemChanged(selectedPos);
     selectedPos = getLayoutPosition();
     notifyItemChanged(selectedPos); 
}

就像导航抽屉和其他RecyclerView项目适配器的护身符一样工作。

注意:请确保使用诸如colabug之类的选择器在布局中使用背景色:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@color/pressed_color" android:state_pressed="true"/>
  <item android:drawable="@color/selected_color" android:state_selected="true"/>
  <item android:drawable="@color/focused_color" android:state_focused="true"/>
</selector>

否则setSelected(..)将不起作用,从而使该解决方案无用。


12
我在行视图上设置了背景可绘制/选择器的情况下使用了此解决方案: <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/pressed_color" android:state_pressed="true"/> <item android:drawable="@color/selected_color" android:state_selected="true"/> <item android:drawable="@color/focused_color" android:state_focused="true"/> </selector>
colabug

1
@zIronManBox:不错,很简单!是否应将onClick方法中的“ selectedPosition”设置为“ selectedPos”?
AJW

3
我无法使用getLayoutPosition()。
ka3ak

3
不要只是使用-1,请使用RecyclerView.NO_POSITION; (是-1)
Martin Marconcini

8
@ ka3ak:getLayoutPosition是ViewHolder类的方法,其对象作为绑定视图方法中的第一个参数传递。因此可以通过vieHolder.getLayoutPosition
Tushar Kathuria

129

更新[2017年7月26日]:

正如Pawan在有关该IDE警告不要使用该固定位置的警告中提到的那样,我刚刚如下修改了我的代码。点击侦听器移至ViewHolder,然后使用getAdapterPosition()方法获取位置

int selected_position = 0; // You have to set this globally in the Adapter class

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Item item = items.get(position);

    // Here I am just highlighting the background
    holder.itemView.setBackgroundColor(selected_position == position ? Color.GREEN : Color.TRANSPARENT);
}

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

    public ViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // Below line is just like a safety check, because sometimes holder could be null,
        // in that case, getAdapterPosition() will return RecyclerView.NO_POSITION
        if (getAdapterPosition() == RecyclerView.NO_POSITION) return;

        // Updating old as well as new positions
        notifyItemChanged(selected_position);
        selected_position = getAdapterPosition();
        notifyItemChanged(selected_position);

        // Do your another stuff for your onClick
    }
}

希望这会有所帮助。


棒极了!不过,我有点困惑,您能帮我实现一个方法吗,扩展这个答案,当您单击已选择的项目时如何执行else语句中您正在做的事情,以便取消选择它:else { holder.itemView.setBackgroundColor(Color.TRANSPARENT); }
iBobb '16

当然可以 @iBobb。对于未选择的项目,即其位置不等于我们的“ selected_position”变量的位置将没有背景。我之所以使用它,是因为顾名思义,RecyclerView会回收每个项目,因此在我们滚动时它为随机行设置了绿色背景,这就是为什么我放置那个ELSE部件。(您可以通过注释掉ELSE部分来进行尝试,然后滚动您的Recycler视图)
2016年

我认为您不理解我的问题。您知道在任何应用程序中,当您选择某些内容时,它都会突出显示。如果再次按住它,它将被取消选择。我们将如何实施呢?目前,我们只能使用您的代码进行选择,并且触摸并按住同一项目不会执行任何操作。
iBobb

有可能,但是为此您必须重写onLongClickListener而不是onClickListener,现在我很忙,因此无法提供完整的代码,但是您基本上必须这样做。
2016年

出于某种原因,点击后需要突出显示时间,大约需要100到200毫秒。知道为什么吗?我在模拟器和棒棒糖电话上体验到了这一点
suku 2016年

14

如果将内容滚动到视图之外然后又移回视图,则实现可能会起作用。当我问到您的问题时,我遇到了类似的问题。

以下文件片段对我有用。我的实现是针对多重选择的,但是我在那儿强加了一个强制单一选择的技巧。(* 1)

// an array of selected items (Integer indices) 
private final ArrayList<Integer> selected = new ArrayList<>();

// items coming into view
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    // each time an item comes into view, its position is checked
    // against "selected" indices
    if (!selected.contains(position)){
        // view not selected
        holder.parent.setBackgroundColor(Color.LTGRAY);
    }
    else
        // view is selected
        holder.parent.setBackgroundColor(Color.CYAN);
}

// selecting items
@Override
public boolean onLongClick(View v) {

        // set color immediately.
        v.setBackgroundColor(Color.CYAN);

        // (*1)
        // forcing single selection here
        if (selected.isEmpty()){
            selected.add(position);
        }else {
            int oldSelected = selected.get(0);
            selected.clear();
            selected.add(position);
            // we do not notify that an item has been selected
            // because that work is done here.  we instead send
            // notifications for items to be deselected
            notifyItemChanged(oldSelected);
        }
        return false;
}

正如指出的在这个链接的问题,为viewHolders设置听众应该onCreateViewHolder完成。我以前忘记提及这一点。


6

我想,我找到了关于如何将RecyclerView与我们需要的所有基本功能一起使用的最佳指南(单点+多重选择,突出显示,波纹,单击并在多重选择中删除等等)。

这是-> http://enoent.fr/blog/2015/01/18/recyclerview-basics/

基于此,我能够创建一个库“ FlexibleAdapter”,该库扩展了SelectableAdapter。我认为这必须是Adapter的责任,实际上您不需要每次都重写Adapter的基本功能,而要让一个库来做,所以您可以重用相同的实现。

这个适配器非常快,开箱即用(您不需要扩展它);您可以为所需的每种视图类型自定义项目;ViewHolder是预定义的:常见事件已实现:单击和长按;它在旋转后仍保持状态,甚至更多

请随意在您的项目中实施它。

https://github.com/davideas/FlexibleAdapter

Wiki也可用。


编写适配器的出色工作,似乎非常有用。唯一的事情是它确实需要一些基本的示例和文档,我什至感到困惑甚至无法启动它并运行它。可能很棒!
Voy

是的,我没有找到足够的信息来开始。即使似乎在注释代码时也找不到API参考。如果没有该库的事先知识,该示例应用程序看起来虽然很广泛且信息丰富,但很难理解。所有用例都绑定在一起,几乎没有迹象表明什么证明了什么,类在整个不同场景中都可以重用,从而导致它们重载信息。我在这里用这些建议创建了一个新问题: github.com/davideas/FlexibleAdapter/issues/120
Voy

Wiki已被完全重写,并且正在完善中。
Davideas

6

看我的解决方案。我想您应该在支架中设置选定的位置,并将其作为“视图标签”传递。该视图应在onCreateViewHolder(...)方法中设置。还有正确的位置来设置侦听器以进行查看,例如OnClickListener或LongClickListener。

请查看下面的示例,并阅读代码注释。

public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.ViewHolder> {
    //Here is current selection position
    private int mSelectedPosition = 0;
    private OnMyListItemClick mOnMainMenuClickListener = OnMyListItemClick.NULL;

    ...

    // constructor, method which allow to set list yourObjectList

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //here you prepare your view 
        // inflate it
        // set listener for it
        final ViewHolder result = new ViewHolder(view);
        final View view =  LayoutInflater.from(parent.getContext()).inflate(R.layout.your_view_layout, parent, false);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //here you set your current position from holder of clicked view
                mSelectedPosition = result.getAdapterPosition();

                //here you pass object from your list - item value which you clicked
                mOnMainMenuClickListener.onMyListItemClick(yourObjectList.get(mSelectedPosition));

                //here you inform view that something was change - view will be invalidated
                notifyDataSetChanged();
            }
        });
        return result;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final YourObject yourObject = yourObjectList.get(position);

        holder.bind(yourObject);
        if(mSelectedPosition == position)
            holder.itemView.setBackgroundColor(Color.CYAN);
        else
            holder.itemView.setBackgroundColor(Color.RED);
    }

    // you can create your own listener which you set for adapter
    public void setOnMainMenuClickListener(OnMyListItemClick onMyListItemClick) {
        mOnMainMenuClickListener = onMyListItemClick == null ? OnMyListItemClick.NULL : onMyListItemClick;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {


        ViewHolder(View view) {
            super(view);
        }

        private void bind(YourObject object){
            //bind view with yourObject
        }
    }

    public interface OnMyListItemClick {
        OnMyListItemClick NULL = new OnMyListItemClick() {
            @Override
            public void onMyListItemClick(YourObject item) {

            }
        };

        void onMyListItemClick(YourObject item);
    }
}

您认为可以将mSelectedPosition声明为static来维护配置更改吗?
萨特什

没有!将其设置为静态是错误的,这是非常错误的
Konrad Krakowiak

是的 这很危险。但是要保持配置更改(尤其是屏幕旋转),我们可以在活动中声明此变量,然后从那里获取它,对吗?
萨特什

有很多解决方案...您可以使用getter和setter,您可以为适配器创建自己的方法saveInstanceState,并从Activity / Fragment
Konrad Krakowiak

4

RecyclerView中没有选择器,例如ListView和GridView,但是您尝试使用以下对我有用的东西

创建一个如下所示的选择器可绘制

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:state_pressed="true">
   <shape>
         <solid android:color="@color/blue" />
   </shape>
</item>

<item android:state_pressed="false">
    <shape>
       <solid android:color="@android:color/transparent" />
    </shape>
</item>
</selector>

然后将此可绘制对象设置为RecyclerView行布局的背景为

android:background="@drawable/selector"

2
这没有什么用。它将在印刷时改变颜色。
Leo Droidcoder

4

通过接口和回调进行决策。创建具有选择和取消选择状态的接口:

public interface ItemTouchHelperViewHolder {
    /**
     * Called when the {@link ItemTouchHelper} first registers an item as being moved or swiped.
     * Implementations should update the item view to indicate it's active state.
     */
    void onItemSelected();


    /**
     * Called when the {@link ItemTouchHelper} has completed the move or swipe, and the active item
     * state should be cleared.
     */
    void onItemClear();
}

在ViewHolder中实现接口:

   public static class ItemViewHolder extends RecyclerView.ViewHolder implements
            ItemTouchHelperViewHolder {

        public LinearLayout container;
        public PositionCardView content;

        public ItemViewHolder(View itemView) {
            super(itemView);
            container = (LinearLayout) itemView;
            content = (PositionCardView) itemView.findViewById(R.id.content);

        }

               @Override
    public void onItemSelected() {
        /**
         * Here change of item
         */
        container.setBackgroundColor(Color.LTGRAY);
    }

    @Override
    public void onItemClear() {
        /**
         * Here change of item
         */
        container.setBackgroundColor(Color.WHITE);
    }
}

回调上的运行状态更改:

public class ItemTouchHelperCallback extends ItemTouchHelper.Callback {

    private final ItemTouchHelperAdapter mAdapter;

    public ItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
        this.mAdapter = adapter;
    }

    @Override
    public boolean isLongPressDragEnabled() {
        return true;
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        return true;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        int swipeFlags = ItemTouchHelper.END;
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        ...
    }

    @Override
    public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
        ...
    }

    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
            if (viewHolder instanceof ItemTouchHelperViewHolder) {
                ItemTouchHelperViewHolder itemViewHolder =
                        (ItemTouchHelperViewHolder) viewHolder;
                itemViewHolder.onItemSelected();
            }
        }
        super.onSelectedChanged(viewHolder, actionState);
    }

    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);
        if (viewHolder instanceof ItemTouchHelperViewHolder) {
            ItemTouchHelperViewHolder itemViewHolder =
                    (ItemTouchHelperViewHolder) viewHolder;
            itemViewHolder.onItemClear();
        }
    }   
}

使用回调创建RecyclerView(示例):

mAdapter = new BuyItemsRecyclerListAdapter(MainActivity.this, positionsList, new ArrayList<BuyItem>());
positionsList.setAdapter(mAdapter);
positionsList.setLayoutManager(new LinearLayoutManager(this));
ItemTouchHelper.Callback callback = new ItemTouchHelperCallback(mAdapter);
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(positionsList);

在iPaulPro的文章中查看更多信息:https ://medium.com/@ipaulpro/drag-and-swipe-with-recyclerview-6a6f0c422efd#.6gh29uaaz


3

这是我的解决方案,您可以设置一个项目(或一个组),然后再次单击以取消选择它:

 private final ArrayList<Integer> seleccionados = new ArrayList<>();
@Override
    public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
        viewHolder.san.setText(android_versions.get(i).getAndroid_version_name());
        if (!seleccionados.contains(i)){ 
            viewHolder.inside.setCardBackgroundColor(Color.LTGRAY);
        }
        else {
            viewHolder.inside.setCardBackgroundColor(Color.BLUE);
        }
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (seleccionados.contains(i)){
                    seleccionados.remove(seleccionados.indexOf(i)); 
                    viewHolder.inside.setCardBackgroundColor(Color.LTGRAY);
                } else { 
                    seleccionados.add(i);
                    viewHolder.inside.setCardBackgroundColor(Color.BLUE);
                }
            }
        });
    }

2

我有同样的问题,我可以通过以下方法解决:

用于在createViewholder内部创建行的xml文件,只需添加以下行:

 android:clickable="true"
 android:focusableInTouchMode="true"
 android:background="?attr/selectableItemBackgroundBorderless"

或如果您使用frameLayout作为行项目的父项,则:

android:clickable="true"
android:focusableInTouchMode="true"
android:foreground="?attr/selectableItemBackgroundBorderless"

在您在点击侦听器中添加的视图持有人内部的Java代码中:

@Override
   public void onClick(View v) {

    //ur other code here
    v.setPressed(true);
 }

1

我在网上找不到解决此问题的好方法,并自己解决了。有很多人遭受这个问题。因此,我想在这里分享我的解决方案。

滚动时,行被回收。因此,选中的复选框和突出显示的行无法正常工作。我通过编写以下适配器类解决了此问题。

我还实施了一个完整的项目。在此项目中,您可以选择多个复选框。包含选定复选框的行将突出显示。更重要的是,这些在滚动时不会丢失。您可以从链接下载它:

https://www.dropbox.com/s/ssm58w62gw32i29/recyclerView_checkbox_highlight.zip?dl=0

    public class RV_Adapter extends RecyclerView.Adapter<RV_Adapter.ViewHolder> {
        public ArrayList<String> list;
        boolean[] checkBoxState;
        MainActivity mainActivity;
        MyFragment myFragment;
        View firstview;

        private Context context;

        FrameLayout framelayout;

        public RV_Adapter() {

      }

        public RV_Adapter(Context context, MyFragment m, ArrayList<String> list ) {
          this.list = list;
          myFragment = m;
          this.context = context;
          mainActivity = (MainActivity) context;
          checkBoxState = new boolean[list.size()];
          // relativeLayoutState = new boolean[list.size()];
        }

        public class ViewHolder extends RecyclerView.ViewHolder  {
            public TextView textView;
            public CheckBox checkBox;
            RelativeLayout relativeLayout;
            MainActivity mainActivity;
            MyFragment myFragment;
            public ViewHolder(View v,MainActivity mainActivity,MyFragment m) {
                super(v);
                textView = (TextView) v.findViewById(R.id.tv_foodname);
                /**/
                checkBox= (CheckBox) v.findViewById(R.id.checkBox);
                relativeLayout = (RelativeLayout)v.findViewById(R.id.relativelayout);
                this.mainActivity = mainActivity;
                this.myFragment = m;
                framelayout = (FrameLayout) v.findViewById(R.id.framelayout);
                framelayout.setOnLongClickListener(m);
            }

        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            firstview = inflater.inflate(R.layout.row, parent, false);
            return new ViewHolder(firstview,mainActivity, myFragment);
        }

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

            holder.textView.setText(list.get(position));

            holder.itemView.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {

              }
            });

            // When action mode is active, checkboxes are displayed on each row, handle views(move icons) on each row are disappered.
            if(!myFragment.is_in_action_mode)
            {

              holder.checkBox.setVisibility(View.GONE);
            }
            else
            {
              holder.checkBox.setVisibility(View.VISIBLE);
              holder.checkBox.setChecked(false);
            }

              holder.checkBox.setTag(position);

              holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                  if(compoundButton.isPressed()) // ekrandan kaybolan checkbox'lar otomatik olarak state degistiriyordu ve bu listener method cagiriliyordu, bunu onlemek icin isPressed() method'u ile kullanici mi basmis diye kontrol ediyorum.
                  {
                    int getPosition = (Integer) compoundButton.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                    checkBoxState[getPosition] = compoundButton.isChecked(); // Set the value of checkbox to maintain its state.
                    //relativeLayoutState[getPosition] = compoundButton.isChecked();

                  if(checkBoxState[getPosition] && getPosition == position )
                    holder.relativeLayout.setBackgroundResource(R.color.food_selected); /** Change background color of the selected items in list view  **/
                  else
                    holder.relativeLayout.setBackgroundResource(R.color.food_unselected); /** Change background color of the selected items in list view  **/
                    myFragment.prepareselection(compoundButton, getPosition, holder.relativeLayout);

                  }
                }
              });
              holder.checkBox.setChecked(checkBoxState[position]);

              if(checkBoxState[position]  )
                holder.relativeLayout.setBackgroundResource(R.color.food_selected); /** Change background color of the selected items in list view  **/
              else
                holder.relativeLayout.setBackgroundResource(R.color.food_unselected);
        }



        @Override
        public int getItemCount() {
            return list.size();
        }

        public void updateList(ArrayList<String> newList){
          this.list = newList;
          checkBoxState = new boolean[list.size()+1];
        }

      public void resetCheckBoxState(){
        checkBoxState = null;
        checkBoxState = new boolean[list.size()];
      }

    }

该应用程序的屏幕截图:

屏幕1 屏幕2 屏幕3 屏幕4


-1

设置private int selected_position = -1;为防止启动时选择任何项目。

 @Override
 public void onBindViewHolder(final OrdersHolder holder, final int position) {
    final Order order = orders.get(position);
    holder.bind(order);
    if(selected_position == position){
        //changes background color of selected item in RecyclerView
        holder.itemView.setBackgroundColor(Color.GREEN);
    } else {
        holder.itemView.setBackgroundColor(Color.TRANSPARENT);
        //this updated an order property by status in DB
        order.setProductStatus("0");
    }
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //status switch and DB update
            if (order.getProductStatus().equals("0")) {
                order.setProductStatus("1");
                notifyItemChanged(selected_position);
                selected_position = position;
                notifyItemChanged(selected_position);
             } else {
                if (order.getProductStatus().equals("1")){
                    //calls for interface implementation in
                    //MainActivity which opens a new fragment with 
                    //selected item details 
                    listener.onOrderSelected(order);
                }
             }
         }
     });
}

-1

只需添加 android:background="?attr/selectableItemBackgroundBorderless"如果您没有背景色,则,但不要忘记使用setSelected方法。如果您有不同的背景色,我就用了(我正在使用数据绑定)。

在onClick函数上设置isSelected

b.setIsSelected(true);

并将其添加到xml;

android:background="@{ isSelected ? @color/{color selected} : @color/{color not selected} }"

-1

选择器:

 <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/Green_10" android:state_activated="true" />
    <item android:drawable="@color/Transparent" />
</selector>

在您的列表项布局中将其设置为背景

   <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:background="@drawable/selector_attentions_list_item"
        android:layout_width="match_parent"
        android:layout_height="64dp">

在您的适配器中,将OnClickListener添加到视图中(onBind方法)

 @Suppress("UNCHECKED_CAST")
    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindItems(item: T) {
            initItemView(itemView, item)
            itemView.tag = item
            if (isClickable) {
                itemView.setOnClickListener(onClickListener)
            }
        }
    }

在onClick事件中,激活视图:

 fun onItemClicked(view: View){
        view.isActivated = true
    }

2
这有2个问题:1)您尚未提供任何方法来撤消回收站中其他项目的激活。2)视图被重用。因此,当滚动时,相同的激活视图可能会向下显示。
Anup Sharma
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.