我有一个RecyclerView,它有一个创建TimePickerDialog的按钮,我需要将选择的时间发送给MainActivity。 如何将其发回?(不是通过单击整个视图,只需从该按钮/对话框中点击)
答案 0 :(得分:0)
使您的RecyclerView适配器实现自定义界面。这是唯一合理和充分的方式。
<强> CODE:强>
<强> RecyclerViewAdapter.java: 强>
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ButtonListener mListener;
public interface ButtonListener {
void onButtonClick(View view, String yourInfo);
}
public void setButtonListener(ButtonListener listener) {
mListener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
.....
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
.....
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final Button mButton;
ViewHolder(View v) {
super(v);
mButton = (Button)v.findViewById(R.id.favouriteButton);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mListener != null)
mListener.onButtonClick(v, "Your info");
}
});
}
}
}
<强> Activity.java:强>
private RecyclerViewAdapter mAdapter;
...
...
mAdapter = new RecyclerViewAdapter(yourParams...);
mAdapter.setButtonListener(new RecyclerViewAdapter.ButtonListener() {
@Override
public void onButtonClick(View view, String yourInfo) {
// Do stuff with yourInfo
}
});
使用您需要的参数定义接口回调&amp;应该这样做。通过这种方式,您可以拦截RecyclerView项目的click事件,并在Activity(正确的方式)而不是适配器中处理它。