Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting DialogFragment from a class extending RecyclerView.ViewHolder

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 ?

like image 506
Lin Lin Avatar asked Mar 15 '23 02:03

Lin Lin


1 Answers

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");
    }
}
like image 166
Emil Avatar answered Apr 07 '23 22:04

Emil