要在RecyclerView上默认选择项目,您可以使用以下方法:
public class MyAdapter extends RecyclerView.Adapter {
private List mData;
private int mSelectedPosition = -1;
private OnItemSelectedListener mListener;
//...
public void setOnItemSelectedListener(OnItemSelectedListener listener) {
mListener = listener;
}
public interface OnItemSelectedListener {
void onItemSelected(int position);
}
//...
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView mTextView;
ViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
mSelectedPosition = getAdapterPosition();
notifyDataSetChanged();
if (mListener != null) {
mListener.onItemSelected(mSelectedPosition);
}
}
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(mData.get(position));
holder.itemView.setSelected(position == mSelectedPosition);
}
MyAdapter adapter = new MyAdapter(data);
adapter.setOnItemSelectedListener(new MyAdapter.OnItemSelectedListener() {
@Override
public void onItemSelected(int position) {
// 处理选中项目的逻辑
}
});
recyclerView.setAdapter(adapter);
这样,当用户点击项目时,它将被选中并更新适配器。您可以通过处理选中项目的逻辑来执行所需的操作。