从扩展RecyclerView.ViewHolder的类中启动DialogFragment [英] Starting DialogFragment from a class extending RecyclerView.ViewHolder

查看:165
本文介绍了从扩展RecyclerView.ViewHolder的类中启动DialogFragment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在recyelerview.viewholder类的onClick()方法中尝试如下.

I tried as below at onClick() method of recyelerview.viewholder class.

SampleDialogFragment扩展了DialogFragment.

SampleDialogFragment used in the sample extends DialogFragment.

@Override
public void onClick(View v)
{
SampleDialogFragment df= new SampleDialogFragment();
df.show(v.getContext().getSupportFragmentManager(), "Dialog");
}

我在v.getContext().getSupportFragmentManager()遇到问题.我无法调用getSupportFragmentManager().

I'm facing problem at v.getContext().getSupportFragmentManager(). I can't call getSupportFragmentManager().

我也尝试了以下方法.

@Override
public void onClick(View v)
{
SampleDialogFragment df= new SampleDialogFragment();
SampleActivity activity = new SampleActivity();
df.show(activity.getSupportFragmentManager(), "Dialog");
}

SampleActivity是附加到回收者视图的活动.它没有显示错误.当我运行该应用程序并崩溃时.

SampleActivity is the activity the recycler view is attached . It shows no error. When I run the app and crash.

日志显示活动已被破坏.

The log shows that the activity has destoryed.

任何解决方案吗?

推荐答案

正确的方法是使用接口.

The proper way is to use an interface.

public interface OnItemClickListener {
    void onItemClicked(View v);
}

并在触发onClick方法时调用接口方法.

And call the interface method when the onClick method is fired.

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

并在您的SampleActivity

public class SampleActivity extends FragmentActivity implements OnItemClickListener {

    @Override
    public void onItemClicked(View v) {
        SampleDialogFragment df= new SampleDialogFragment();
        df.show(getSupportFragmentManager(), "Dialog");
    }
}

这篇关于从扩展RecyclerView.ViewHolder的类中启动DialogFragment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆