我在recyelerview.viewholder类的onClick()方法中尝试了如下.
示例中使用的SampleDialogFragment扩展了DialogFragment.
@Override
public void onClick(View v)
{
SampleDialogFragment df= new SampleDialogFragment();
df.show(v.getContext().getSupportFragmentManager(), "Dialog");
}
我在v.getContext().getSupportFragmentManager()面临问题.我无法调用getSupportFragmentManager().
我也试过如下.
@Override
public void onClick(View v)
{
SampleDialogFragment df= new SampleDialogFragment();
SampleActivity activity = new SampleActivity();
df.show(activity.getSupportFragmentManager(), "Dialog");
}
SampleActivity是回收器视图附加的活动.它没有显示错误.当我运行应用程序并崩溃.
日志显示活动已经破坏.
有解决方案吗
解决方法:
正确的方法是使用接口.
public interface OnItemClickListener {
void onItemClicked(View v);
}
并在触发onClick方法时调用接口方法.
public class YourListAdapter extends RecyclerView.Adapter<...>
//your code
private OnItemClickListener listener;
public YourListAdapter(OnItemClickListener listener /*your additional parameters*/) {
this.listener = listener;
//...
}
@Override
public void onClick(View v){
listener.onItemClicked(View v);
}
}
您必须从SampleActivity传递OnItemClickListener接口实例
并让它在您的SampleActivity中实现它
public class SampleActivity extends FragmentActivity implements OnItemClickListener {
@Override
public void onItemClicked(View v) {
SampleDialogFragment df= new SampleDialogFragment();
df.show(getSupportFragmentManager(), "Dialog");
}
}