我在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);
}
}
你必须从OnItemClickListener
传递SampleActivity
接口实例
并让它在你的SampleActivity
中实现它
public class SampleActivity extends FragmentActivity implements OnItemClickListener {
@Override
public void onItemClicked(View v) {
SampleDialogFragment df= new SampleDialogFragment();
df.show(getSupportFragmentManager(), "Dialog");
}
}
我使用它最简单的方法
public class AdapterProduct extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
FragmentManager FragManager ;
// in constructor
public AdapterProduct(Context context, RecyclerView view ,
ArrayList<Product> items , FragmentManager getSupportFragmentManager) {
this.items = items;
ctx = context;
FragManager = getSupportFragmentManager;
lastItemViewDetector(view);
}
}
在onClick
@Override
public void onClick(View v)
{
SampleDialogFragment df= new SampleDialogFragment();
SampleActivity activity = new SampleActivity();
df.show(FragManager , "Dialog");
}
在您的MainActivity中或您设置recycleview的位置
AdapterProduct mAdapter = new AdapterProduct(MainActivity.this, rv_Daily_Deals,
BeanProduct,getSupportFragmentManager());