在您的RecyclerView的Adapter类中,实现一个回调接口。这可以让您在单击RecyclerView项时向另一个Activity发送数据。
首先,在Adapter类中创建一个接口。这里我们将其命名为ItemClicked。然后,在您的ViewHolder类中为RecyclerView项设置单击侦听器。在单击事件中调用ItemClicked接口的方法,并将需要传递的数据作为参数传递。
public class MyAdapter extends RecyclerView.Adapter {
private List mDataList;
private ItemClicked mCallback; // Our callback
public MyAdapter(List data, ItemClicked listener) {
mDataList = data;
mCallback = listener;
}
public interface ItemClicked {
void onItemClicked(String text);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mTextView;
public MyViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.text_view);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// Get the text from the TextView
String text = mTextView.getText().toString();
// Pass the text to the callback interface
mCallback.onItemClicked(text);
}
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
MyData data = mDataList.get(position);
holder.mTextView.setText(data.getText());
}
@Override
public int getItemCount() {
return mDataList.size();
}
}
现在,我们需要在另一个Activity中实现ItemClicked接口,并在onItemClicked方法中接收传递的数据。在其中,我们可以将该数据设置为我们TextView的text。
public class SecondActivity extends AppCompatActivity implements MyAdapter.ItemClicked {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mTextView = findViewById(R.id.text_view);
}
@Override
public void onItemClicked(String text) {
mTextView.setText(text);
}
}
最后,我们需要将我们的Adapter和接口实例化,并将其传递给RecyclerView。
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private List mDataList;
@