Starting DialogFragment from a class extending RecyclerView.ViewHolder

╄→尐↘猪︶ㄣ 提交于 2019-12-06 06:00:43

问题


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

SampleDialogFragment used in the sample extends DialogFragment.

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

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

I also tried as below .

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

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.

Any solution ?


回答1:


The proper way is to use an interface.

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

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);
}
}

You have to pass the OnItemClickListener Interface instance from SampleActivity

And have it implement it in your SampleActivity

public class SampleActivity extends FragmentActivity implements OnItemClickListener {

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



回答2:


the easiest way i use it

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);
    }
}

in onClick

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

in your MainActivity or where u set your recycleview

AdapterProduct mAdapter = new AdapterProduct(MainActivity.this, rv_Daily_Deals,
BeanProduct,getSupportFragmentManager());


来源:https://stackoverflow.com/questions/33889477/starting-dialogfragment-from-a-class-extending-recyclerview-viewholder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!