,可以通过以下步骤实现:
下面是一个示例代码:
// ViewHolder类
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView checkboxTextView;
public MyViewHolder(View itemView) {
super(itemView);
checkboxTextView = itemView.findViewById(R.id.checkbox_textview);
checkboxTextView.setClickable(true);
}
}
// Adapter类
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<String> data;
public MyAdapter(List<String> data) {
this.data = data;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
String item = data.get(position);
holder.checkboxTextView.setText(item);
holder.checkboxTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isSelected = holder.checkboxTextView.isSelected();
holder.checkboxTextView.setSelected(!isSelected);
// 执行其他操作
}
});
}
@Override
public int getItemCount() {
return data.size();
}
}
// 在Activity或Fragment中使用RecyclerView
public class MyActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List<String> data = new ArrayList<>();
// 添加数据到data
adapter = new MyAdapter(data);
recyclerView.setAdapter(adapter);
// 刷新后停止滚动
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, 0);
}
}
以上代码示例中,我们在RecyclerView的列表项中使用了一个TextView作为选框,并在点击事件中切换了选中状态。在Activity或Fragment中,我们通过调用RecyclerView的LayoutManager的smoothScrollToPosition方法来实现刷新后停止滚动。
腾讯云相关产品推荐:
领取专属 10元无门槛券
手把手带您无忧上云