【问题标题】:Cannot highlight items in RecyclerView with selectors无法使用选择器突出显示 RecyclerView 中的项目
【发布时间】:2021-01-25 09:33:03
【问题描述】:

我只想在按下项目时突出显示它。

我在下面有选择器 (@drawable/expandable_menu)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:exitFadeDuration="@android:integer/config_mediumAnimTime">
<item android:drawable="@color/purple_200" android:state_pressed="true" />
<item android:drawable="@color/purple_500" android:state_selected="true" />
<item android:drawable="@color/chat" android:state_activated="true" />
<item android:drawable="@color/transparent"/>
</selector>

在我的 onclick 监听器中,我选择了这个项目

RecyclerView XML:

<androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="70dp"
        android:id="@+id/chat_messages"
        app:stackFromEnd="true"
        android:clickable="true"
        android:focusableInTouchMode="true"
        android:background="@drawable/expandable_menu"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        android:focusable="true">

消息 XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:paddingTop="10dp"
android:layout_gravity="left"
>

<TextView
    android:id="@+id/chat_msg_send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="this is me"
    android:textColor="@color/black"
    android:textSize="16dp"
    android:background="@color/cardview_shadow_start_color"
    android:padding="10dp"
    android:layout_alignParentTop="true" />
 </RelativeLayout>

我关注了这个答案 (https://stackoverflow.com/a/30046476) 但没有成功

【问题讨论】:

    标签: android xml android-recyclerview


    【解决方案1】:

    您必须将OnClickListener 设置为View,将选择器设置为背景。我看到你为TextView(孩子)设置了选择器,你是设置onClick到这个View还是整个itemView(在你的情况下是rootRelativeLayout)?

    您也可以尝试为TextView 添加android:duplicateParentState - 这应该使TextView 在按下父级时绘制按下状态,而不仅仅是TextView 本身(当没有OnClickListener 时根本不可点击设置)

    【讨论】:

    • 我将选中状态和 onClickListener 设置为 holder.itemView 元素
    【解决方案2】:
    In this tutorial, i would explain how you can load a recyclerview with the first item selected (background color changed) and also make the background of the other items changed when clicked.
    Follow the step by step process.
    
    [Highlighted selected item in recycler view screenshot][1]
    [1]:   https://i.stack.imgur.com/hHP0W.png
    
    You can see full steps of RecyclerView Highlighted items
    
    
    Start by creating a new Android Studio project. Go to File -> New Project.
    Open your color file `(res -> values -> colors.xml)`. Paste the below code.
    colors.xml
    
    >     <resources>
    >         <color name="colorPrimaryLight">#07C4AF</color>
    >         <color name="colorPrimary">#035F56</color>
    >         <color name="colorPrimaryDark">#00574B</color>
    >         <color name="colorAccent">#D81B60</color>
    >      
    >     </resources>
    
     **create a new android resource layout. Right click on your project file, select New -> Android Resource Layout . give it the name “recycler_items”.**
    
    **recycler_items.xml**
      
    
      <android.support.v7.widget.CardView
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/cardview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            card_view:contentPaddingLeft="18dp"
            card_view:contentPaddingRight="18dp"
            card_view:cardCornerRadius="15dp"
            card_view:cardElevation="7dp"
            card_view:cardBackgroundColor="@color/colorPrimary"
            android:layout_marginLeft="8dp"
         
            >
         
            <TextView
                android:id="@+id/tv_pets"
                android:layout_gravity="center"
                android:textSize="15dp"
                android:layout_marginTop="5dp"
                android:layout_marginBottom="5dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Pet Name"
                android:textColor="#fff"/>
         
        </android.support.v7.widget.CardView>
         
    
     **Right click on your project file, select New -> Java Class. Give it the name “RecyclerAdapter“. This is the adapter that would be used to populate our recyclerview.**
    
           
        
        import android.content.Context;
        import android.support.v7.widget.CardView;
        import android.support.v7.widget.RecyclerView;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.ImageView;
        import android.widget.TextView;
        import java.util.List;
         
        public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>  {
         
            private List<Pets> petsList;
            private Context context;
            private static int lastClickedPosition = -1;
            private int selectedItem;
         
            public RecyclerAdapter(Context context, List<Pets> petsList) {
                this.context = context;
                this.petsList = petsList;
                selectedItem = 0;
            }
         
            @Override
            public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.recycler_items, parent, false);
         
                return new MyViewHolder(itemView);
            }
         
            @Override
            public void onBindViewHolder(final MyViewHolder holder, final int position) {
                holder.itemView.setTag(petsList.get(position));
                holder.name.setText(petsList.get(position).getName());
         
                holder.cardView.setCardBackgroundColor(context.getResources().getColor(R.color.colorPrimaryLight));
         
                if (selectedItem == position) {
                    holder.cardView.setCardBackgroundColor(context.getResources().getColor(R.color.colorPrimaryDark));
                }
         
         
         
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
         
                        int previousItem = selectedItem;
                        selectedItem = position;
         
                        notifyItemChanged(previousItem);
                        notifyItemChanged(position);
         
         
         
                    }
                });
         
            }
         
         
            @Override
            public int getItemCount() {
                return petsList.size();
            }
         
         
         
         
            public class MyViewHolder extends RecyclerView.ViewHolder {
                public TextView name;
         
                public CardView cardView;
         
                public MyViewHolder(View view) {
                    super(view);
                    name = (TextView) view.findViewById(R.id.tv_pets);
                    cardView = (CardView) view.findViewById(R.id.cardview);
         
                }
            }
         
        }
        
    > Lets create our model class that holds information about the pets
    
     
    
    Pets.java
    
     package androidnoon.recyclerview.select;
     public class Pets {
         
        private int id;
        private String Name;
        private String Description;
     
        public Pets(int id, String name, String description) {
            this.id = id;
            Name = name;
            Description = description;
        }
     
        public int getId() {
            return id;
        }
     
        public void setId(int id) {
            this.id = id;
        }
     
        public String getName() {
            return Name;
        }
     
        public void setName(String name) {
            Name = name;
        }
     
        public String getDescription() {
            return Description;
        }
     
        public void setDescription(String description) {
            Description = description;
        }
    }
          activity_main.xml
        
       <android.support.design.widget.CoordinatorLayout   
    
     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:layout_width="match_parent" 
     android:layout_height="match_parent"  
      tools:context=".MainActivity">
    
     <android.support.design.widget.AppBarLayout android:layout_width="match_parent" 
    android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay">
             
     <android.support.v7.widget.Toolbar
     android:id="@+id/toolbar" 
     android:layout_width="match_parent"
     android:layout_height="?attr/actionBarSize"
     android:background="?attr/colorPrimary" 
     app:popupTheme="@style/AppTheme.PopupOverlay" />
             
      </android.support.design.widget.AppBarLayout>
             
        <android.support.constraint.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:layout_width="match_parent" 
    android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context=".MainActivity" 
    tools:showIn="@layout/activity_main">
                    <android.support.v7.widget.RecyclerView 
     android:id="@+id/RvPets"
     android:layout_marginTop="20dp"
     android:layout_width="match_parent" 
     android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>
             
                </android.support.constraint.ConstraintLayout>
             
             
            </android.support.design.widget.CoordinatorLayout>
    
     
    
        **MainActivity.java**
    import android.content.Context;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
     
    import java.util.ArrayList;
    import java.util.List;
     
    public class MainActivity extends AppCompatActivity {
     
        RecyclerView RvPets;
    
        List<Pets> petsList = new ArrayList<>();
        RecyclerAdapter recyclerAdapter;
     
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
     
            recyclerAdapter = new RecyclerAdapter(MainActivity.this, petsList);
            RvPets = (RecyclerView) findViewById(R.id.RvPets);
     
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
     
            RvPets.setLayoutManager(linearLayoutManager);
     
            RvPets.setAdapter(recyclerAdapter);
            preparePetsData();
     
        }
     
        private void preparePetsData() {
    
            Pets pet = new Pets(1, "Cat", "Cute, has 4 legs");
    
            petsList.add(pet);
     
            pet = new Pets(2, "Bird", "Can Fly, has 2 legs");
    
            petsList.add(pet);
     
            pet = new Pets(3, "Dog", "Cute, has 4 legs");
    
            petsList.add(pet);
     
            pet = new Pets(4, "Fish", "has no leg");
    
            petsList.add(pet);
     
            pet = new Pets(5, "Hamster", "Cute, has 4 legs");
            petsList.add(pet);
     
            recyclerAdapter.notifyDataSetChanged();
     
        }
     
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }
     
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
     
            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
     
            return super.onOptionsItemSelected(item);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 2020-08-30
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多