RecyclerView 是 Android 开发中常用的一个控件,用于展示大数据列表。它是 ListView 的升级版,具有更高的性能和更好的灵活性。
在 RecyclerView 中高亮显示选定行可以通过以下步骤实现:
RecyclerView recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> data;
private int selectedItem = RecyclerView.NO_POSITION; // 初始值为未选中任何行
public MyAdapter(List<String> data) {
this.data = data;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textView);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final String item = data.get(position);
holder.textView.setText(item);
// 设置选定行的高亮样式
if (position == selectedItem) {
holder.itemView.setBackgroundColor(Color.YELLOW);
} else {
holder.itemView.setBackgroundColor(Color.TRANSPARENT);
}
// 点击行时更新选中状态
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectedItem = position;
notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return data.size();
}
}
MyAdapter adapter = new MyAdapter(dataList);
recyclerView.setAdapter(adapter);
通过以上步骤,就能够在 RecyclerView 中实现选定行的高亮显示效果。用户点击某一行时,该行会被高亮显示,其他行则恢复为普通样式。
领取专属 10元无门槛券
手把手带您无忧上云