【问题标题】:CardView selected background color in RecyclerViewCardView 在 RecyclerView 中选择了背景颜色
【发布时间】:2015-01-27 18:15:30
【问题描述】:

我正在尝试使用 CardViews 编写 RecyclerView 并使用 CAB 尝试在选择时删除多个卡。如何为所选卡提供背景颜色。我正在尝试使用 statelistdrawable 如下:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_activated="true" android:drawable="@color/primary_dark" />

    <item android:drawable="@android:color/transparent" />

</selector>

并将其应用于 CardView 布局:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
android:background="@drawable/statelist_item_background"
        card_view:cardCornerRadius="10dp"
    card_view:cardElevation="10dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"


    >


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"

        >

        <ImageView
            android:id="@+id/imageView"
            android:tag="image_tag"
            android:layout_width="72dp"
            android:layout_height="100dp"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/one"/>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:layout_weight="2"
            android:orientation="vertical"
            >

            <TextView
                android:id="@+id/textViewName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="10dp"
                android:text="Large Text"
                android:textAppearance="?android:attr/textAppearanceLarge"/>

            <TextView
                android:id="@+id/textViewEmail"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="10dp"

                android:text="Medium Text"
                android:textAppearance="?android:attr/textAppearanceMedium"/>

        </LinearLayout>
    </LinearLayout>

</android.support.v7.widget.CardView>

下面是我的适配器的代码

public class modeladapter extends RecyclerView.Adapter<modeladapter.myholder> {

    ArrayList<MyModel> arraylist;
SparseBooleanArray selecteditems;
    public modeladapter(ArrayList<MyModel> ar) {
        arraylist=ar;
        selecteditems=new SparseBooleanArray();
    }

    public void removeData(int position) {
        arraylist.remove(position);
        notifyItemRemoved(position);
    }

    public MyModel getItem(int position) {
        return arraylist.get(position);
    }

    public void addData(MyModel newModelData, int position) {
        arraylist.add(position, newModelData);
        notifyItemInserted(position);
    }

    public void toggleSelection(int pos) {
        if (selecteditems.get(pos, false)) {
            selecteditems.delete(pos);
        }
        else {
            selecteditems.put(pos, true);
        }
        notifyItemChanged(pos);
    }

    public void clearSelections() {
        selecteditems.clear();
        notifyDataSetChanged();
    }

    public int getSelectedItemCount() {
        return selecteditems.size();
    }

    public List<Integer> getSelectedItems() {
        List<Integer> items = new ArrayList<Integer>(selecteditems.size());
        for (int i = 0; i < selecteditems.size(); i++) {
            items.add(selecteditems.keyAt(i));
        }
        return items;
    }





    @Override
    public modeladapter.myholder onCreateViewHolder(ViewGroup viewGroup, int i) {
        LayoutInflater lf=LayoutInflater.from(viewGroup.getContext());

            View v = lf.inflate(R.layout.card_lay, viewGroup, false);

//            v.setOnClickListener(Activity_Main.listener);
            myholder m=new myholder(v);
            return m;



    }


    @Override
    public void onBindViewHolder(modeladapter.myholder m, int i) {

                m.cimage.setImageResource(arraylist.get(i).url);
                m.email.setText(arraylist.get(i).email);
                m.name.setText(arraylist.get(i).name);
m.itemView.setActivated(selecteditems.get(i,false));

         }

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

    public static class myholder extends RecyclerView.ViewHolder
    {
        ImageView cimage;
        TextView name,email;

        public myholder(View itemView) {
            super(itemView);
            cimage= (ImageView) itemView.findViewById(R.id.imageView);
            name= (TextView) itemView.findViewById(R.id.textViewName);
            email= (TextView) itemView.findViewById(R.id.textViewEmail);
            if(itemView.isActivated())
                itemView.setBackgroundColor(itemView.getContext().getResources().getColor(R.color.primary_dark));
            else
                itemView.setBackgroundColor(Color.parseColor("#ffffff"));
        }
    }

请更新我如何更改所选项目的背景颜色。 谢谢

【问题讨论】:

  • 你解决了吗?
  • @JaredBurrows 我能做到。
  • @JaredBurrows 给了我一些关于如何完成的想法。

标签: android


【解决方案1】:

您不一定需要StateListDrawable 您需要在适配器中有一个方法来检查选择:

sparseArray.valueAt(i).isSelected()

然后在你的RecylcerView.Adapter,更改:

if (itemView.isActivated())
    itemView.setBackgroundColor(itemView.getContext().getResources().getColor(R.color.primary_dark));
else
    itemView.setBackgroundColor(Color.parseColor("#ffffff"));

To(你需要更改cardView,而不是itemView):

 viewHolder.cardView.setCardBackgroundColor(sparseArray.valueAt(i).isSelected() ? Color.LTGRAY : Color.WHITE);

【讨论】:

  • 检查适配器中选择的方法在哪里?在 ViewHolder() 或 onBindViewHolder() 中?您可以在上面进行编辑以显示示例吗?
【解决方案2】:

对于这个问题的新手来说,值得注意的是,从支持库 v24 开始,CardView 现在支持 ColorStateList。 (注意:这是颜色状态列表,不是可绘制状态列表)

这是链接: https://code.google.com/p/android/issues/detail?id=78198

【讨论】:

  • 那么假设我想为它所拥有的添加一个可选择的颜色,我该怎么做呢?
  • @androiddeveloper 看看你下面的答案;)(我猜你在这条评论之后发布了你的答案......)
  • 这更像是一种解决方法。我希望你有一个更正式、更好的解决方案。
【解决方案3】:
card_view:cardBackgroundColor="@color/statelist_item_background"

【讨论】:

    【解决方案4】:

    而不是改变 CardView 背景颜色, 更改 CardView 内的 LinearLayout:

    <android.support.v7.widget.CardView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="10dp"
    card_view:cardElevation="10dp"
    android:layout_marginTop="5dp"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp">
    
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="@drawable/statelist_item_background">
    
        <ImageView
            android:id="@+id/imageView"
            android:tag="image_tag"
            android:layout_width="72dp"
            android:layout_height="100dp"
            android:layout_margin="5dp"
            android:layout_weight="1"
            android:src="@drawable/one"/>
    
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:layout_weight="2"
            android:orientation="vertical"
            >
    
            <TextView
                android:id="@+id/textViewName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="10dp"
                android:text="Large Text"
                android:textAppearance="?android:attr/textAppearanceLarge"/>
    
            <TextView
                android:id="@+id/textViewEmail"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="10dp"
    
                android:text="Medium Text"
                android:textAppearance="?
                android:attr/textAppearanceMedium"/>
    
        </LinearLayout>
    </LinearLayout>
    

    【讨论】:

      【解决方案5】:

      有多种方法可以做到这一点。以下是如何以编程方式执行此操作:

      使用您自己的自定义卡片视图:

      class SelectableCardView : MaterialCardView {
          @ColorInt
          private var unselectedBackgroundColor = 0
      
          @ColorInt
          private var selectedBackgroundColor = 0
      
          constructor(context: Context?) : super(context) {
              unselectedBackgroundColor = cardBackgroundColor.defaultColor
              setCardBackgroundColor(ColorStateList(arrayOf(intArrayOf(android.R.attr.state_selected), IntArray(0)), intArrayOf(selectedBackgroundColor, unselectedBackgroundColor)))
          }
      
          constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
              unselectedBackgroundColor = cardBackgroundColor.defaultColor
              setCardBackgroundColor(ColorStateList(arrayOf(intArrayOf(android.R.attr.state_selected), IntArray(0)), intArrayOf(selectedBackgroundColor, unselectedBackgroundColor)))
          }
      
          constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
              unselectedBackgroundColor = cardBackgroundColor.defaultColor
              setCardBackgroundColor(ColorStateList(arrayOf(intArrayOf(android.R.attr.state_selected), IntArray(0)), intArrayOf(selectedBackgroundColor, unselectedBackgroundColor)))
          }
      
          init {
              selectedBackgroundColor = ContextCompat.getColor(context, R.color....)
          }
      }
      

      或者在充气的时候,从外面自己设置颜色:

      val cardView = result!!.cardView
      val selectedBackgroundColor = ContextCompat.getColor(inflater.context, R.color....)
      val unselectedBackgroundColor = cardView .cardBackgroundColor.defaultColor
      cardView.setCardBackgroundColor(ColorStateList(arrayOf(intArrayOf(android.R.attr.state_selected), IntArray(0)),intArrayOf(selectedBackgroundColor, unselectedBackgroundColor)))
      

      当然,您可以通过 XML 设置卡片背景颜色,但您必须同时设置默认颜色。我不推荐它,因为它可能会在未来发生变化,就像最近一样。

      例如,过去是cardview_dark_background,在深色主题上改为design_dark_default_color_background,在普通主题上是cardview_light_background,改为design_default_color_background

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-04
        • 2020-10-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多