Starting DialogFragment from a class extending Rec

2020-07-18 04:23发布

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 ?

2条回答
戒情不戒烟
2楼-- · 2020-07-18 05:07

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());
查看更多
该账号已被封号
3楼-- · 2020-07-18 05:17

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");
    }
}
查看更多
登录 后发表回答