如何在 Android RecyclerView 中正确突出显示选中的项目?


此示例演示了如何在 Android RecyclerView 上正确突出显示选中的项目。

步骤 1 - 在 Android Studio 中创建一个新项目,转到文件 ⇒ 新建项目,并填写所有必需的详细信息以创建新项目。

在 build.gradle (Module: app) 中添加以下依赖项

implementation 'com.android.support:recyclerview-v7:28.0.0'

步骤 2 - 将以下代码添加到 res/layout/activity_main.xml 中。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="4dp"
   tools:context=".MainActivity">
   <androidx.recyclerview.widget.RecyclerView
      android:id="@+id/recyclerView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:paddingBottom="8dp" />
</RelativeLayout>

步骤 3 - 创建一个布局资源文件 (list_layout.xml) 并添加以下代码 -

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/container"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="@drawable/background_selector"
   android:padding="16dp">
   <TextView
      android:id="@+id/awardTitle"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="10dp"
      android:text="New Text"
      android:textSize="18sp"
      android:textStyle="bold" />
   <TextView
      android:id="@+id/awardYear"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/awardTitle"
      android:layout_alignStart="@+id/awardTitle"
      android:layout_marginTop="20dp"
      android:text="New Text"
      android:textColor="#000" />
   <TextView
      android:id="@+id/playerName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentEnd="true"
      android:text="New Text" />
</RelativeLayout>

步骤 4 - 创建如下所述的可绘制资源文件并添加相应的代码 -

background_selector.xml -

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:drawable="@color/colorAccent" android:state_pressed="false" android:state_selected="true" />
   <item android:drawable="@android:color/white" android:state_selected="false" />
</selector>

line_divider.xml -

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
   <size
      android:width="2dp"
      android:height="2dp" />
   <solid android:color="@color/colorPrimaryDark" />
</shape>

步骤 5 - 创建如下所述的 Java 类文件并添加相应的代码 -

ItemObject -

class ItemObject {
   private String awardTitle;
   private String awardYear;
   private String player;
   ItemObject(String awardTitle, String awardYear, String player) {
      this.awardTitle = awardTitle;
      this.awardYear = awardYear;
      this.player = player;
   }
   String getAwardTitle() {
      return awardTitle;
   }
   String getAwardYear() {
      return awardYear;
   }
   String getPlayer() {
      return player;
   }
}

RecyclerViewAdapter -

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerViewHolders> {
   private List<ItemObject> itemList;
   RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
      this.itemList = itemList;
   }
   @NonNull
   @Override
   public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
      View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, null);
      return new RecyclerViewHolders(layoutView);
   }
   @Override
   public void onBindViewHolder(RecyclerViewHolders holder, int position) {
      holder.awardTitle.setText("Award Title: " + itemList.get(position).getAwardTitle());
      holder.awardYear.setText("Award Year: " + itemList.get(position).getAwardYear());
      holder.player.setText("Player Name: " + itemList.get(position).getPlayer());
   }
   @Override
   public int getItemCount() {
      return this.itemList.size();
   }
}

RecyclerViewHolders -

import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
class RecyclerViewHolders extends RecyclerView.ViewHolder implements
View.OnClickListener {
   TextView awardTitle;
   TextView awardYear;
   TextView player;
   private SparseBooleanArray selectedItems = new SparseBooleanArray();
   RecyclerViewHolders(View itemView) {
      super(itemView);
      itemView.setOnClickListener(this);
      awardTitle = itemView.findViewById(R.id.awardTitle);
      awardYear = itemView.findViewById(R.id.awardYear);
      player = itemView.findViewById(R.id.playerName);
   }
   @Override
   public void onClick(View view) {
      if (selectedItems.get(getAdapterPosition(), false)) {
         selectedItems.delete(getAdapterPosition());
         view.setSelected(false);
      }
       else {
         selectedItems.put(getAdapterPosition(), true);
         view.setSelected(true);
      }
   }
}

SimpleItemDecoration -

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
class SimpleItemDecoration extends RecyclerView.ItemDecoration {
   private Drawable drawable;
   SimpleItemDecoration(Context context) {
      drawable = ContextCompat.getDrawable(context, R.drawable.line_divider);
   }
   @Override
   public void onDrawOver(@NonNull Canvas canvas, RecyclerView parent, @NonNull RecyclerView.State state) {
      int left = parent.getPaddingLeft();
      int right = parent.getWidth() - parent.getPaddingRight();
      int childCount = parent.getChildCount();
      for (int i = 0; i < childCount; i++) {
         View child = parent.getChildAt(i);
         RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
         int top = child.getBottom() + params.bottomMargin;
         int bottom = top + drawable.getIntrinsicHeight();
         drawable.setBounds(left, top, right, bottom);
         drawable.draw(canvas);
      }
   }
}

步骤 6 - 将以下代码添加到 src/MainActivity.java 中

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      RecyclerView recyclerView = findViewById(R.id.recyclerView);
      recyclerView.addItemDecoration(new SimpleItemDecoration(this));
      LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
      recyclerView.setLayoutManager(layoutManager);
      List<ItemObject> posts = returnListItems();
      RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainActivity.this, posts);
      recyclerView.setAdapter(adapter);
   }
   private List<ItemObject> returnListItems() {
      List<ItemObject> items = new ArrayList<>();
      items.add(new ItemObject("Ballon'd'or", "2007", "Ricardo KaKa"));
      items.add(new ItemObject("Ballon'd'or", "2008", "Cristiano Ronaldo"));
      items.add(new ItemObject("Ballon'd'or", "2009 - 2012, 2015", "Lionel Messi"));
      items.add(new ItemObject("Ballon'd'or", "2013, 2014, 2016, 2017", "Cristiano Ronaldo"));
      items.add(new ItemObject("Ballon'd'or", "2018", "Luca Modric"));
      items.add(new ItemObject("Ballon'd'or", "2019", "Haven't decided yet"));
      return items;
   }
}

步骤 7 - 将以下代码添加到 androidManifest.xml 中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

让我们尝试运行您的应用程序。我假设您已将您的实际 Android 移动设备连接到您的计算机。要从 Android Studio 运行应用程序,请打开您的一个项目活动文件,然后单击工具栏中的运行  图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕 -

点击 这里 下载项目代码。

更新于: 2019年11月22日

3K+ 次查看

启动你的 职业生涯

通过完成课程获得认证

开始
广告