点击RecyclerView的不同条目,且每个条目有一个imageview与两个textview,点击条目出现其中的text view的信息
时间: 2023-05-20 09:05:48 浏览: 159
您可以使用RecyclerView的ItemClickListener来实现这个功能。在RecyclerView的Adapter中,您可以为每个条目设置一个点击事件监听器。当用户点击一个条目时,您可以获取该条目的位置,并从数据源中获取相应的文本信息,然后将其显示在TextView中。以下是一个示例代码:
```
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<MyData> mDataList;
private OnItemClickListener mListener;
public MyAdapter(List<MyData> dataList, OnItemClickListener listener) {
mDataList = dataList;
mListener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
MyData data = mDataList.get(position);
holder.mImageView.setImageResource(data.getImageResId());
holder.mTextView1.setText(data.getText1());
holder.mTextView2.setText(data.getText2());
}
@Override
public int getItemCount() {
return mDataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView mImageView;
public TextView mTextView1;
public TextView mTextView2;
public ViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.image_view);
mTextView1 = itemView.findViewById(R.id.text_view_1);
mTextView2 = itemView.findViewById(R.id.text_view_2);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (mListener != null) {
mListener.onItemClick(getAdapterPosition(), mTextView1.getText().toString());
}
}
}
public interface OnItemClickListener {
void onItemClick(int position, String text);
}
}
```
在Activity或Fragment中,您可以创建一个实现OnItemClickListener接口的监听器,并将其传递给Adapter。当用户点击一个条目时,Adapter将调用监听器的onItemClick方法,并将该条目的位置和文本信息作为参数传递。您可以在该方法中获取文本信息,并将其显示在TextView中。
```
public class MyActivity extends AppCompatActivity implements MyAdapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private MyAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<MyData> dataList = new ArrayList<>();
// add data to dataList
mAdapter = new MyAdapter(dataList, this);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void onItemClick(int position, String text) {
// display text in TextView
TextView textView = findViewById(R.id.text_view);
textView.setText(text);
}
}
```
阅读全文