安卓RecyclerView 单选
时间: 2023-11-28 16:04:09 浏览: 62
Recyclerview的单个选中
3星 · 编辑精心推荐
实现RecyclerView列表单选功能的步骤如下:
1.在RecyclerView的适配器中添加一个变量来保存当前选中的位置,例如selPos。
2.在适配器的onBindViewHolder方法中,根据当前位置是否为selPos来设置单选框的状态。
3.在适配器的构造方法中添加一个接口,用于监听单选框的点击事件。
4.在Activity或Fragment中实现该接口,并在回调方法中更新selPos的值,并调用适配器的notifyDataSetChanged方法刷新列表。
下面是一个简单的示例代码:
```java
public class SingleChoiceAdapter extends RecyclerView.Adapter<SingleChoiceAdapter.ViewHolder> {
private List<String> mData;
private int mSelPos = -1;
private OnItemClickListener mListener;
public SingleChoiceAdapter(List<String> data, OnItemClickListener listener) {
mData = data;
mListener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_single_choice, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.mTextView.setText(mData.get(position));
holder.mRadioButton.setChecked(position == mSelPos);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSelPos = position;
notifyDataSetChanged();
mListener.onItemClick(position);
}
});
}
@Override
public int getItemCount() {
return mData.size();
}
public int getSelPos() {
return mSelPos;
}
public interface OnItemClickListener {
void onItemClick(int position);
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
RadioButton mRadioButton;
ViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.text_view);
mRadioButton = itemView.findViewById(R.id.radio_button);
}
}
}
```
在Activity或Fragment中使用该适配器:
```java
public class MainActivity extends AppCompatActivity implements SingleChoiceAdapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private SingleChoiceAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
List<String> data = new ArrayList<>();
data.add("Item 1");
data.add("Item 2");
data.add("Item 3");
data.add("Item 4");
data.add("Item 5");
mAdapter = new SingleChoiceAdapter(data, this);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void onItemClick(int position) {
Toast.makeText(this, "Selected position: " + position, Toast.LENGTH_SHORT).show();
}
}
```
阅读全文