尝试从Recycler Adapter导航到片段时如何调用getSupportFragmentManager()

时间:2018-07-25 11:37:16

标签: android fragment recycler-adapter

I am calling Recycler Adapter from Fragment not from acvity

当我单击Recyclerview中的项目时,我想导航到另一个Fragment

因此,我在onClickListner()中写了Adapter

private View.OnClickListener onClickListener(final int position){
    return new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            try{

                activityType = context.getActivityFragmentTag(EmpConstants.WorkType.Entry);
                fragment = new Entry_Fragment();
                FragmentManager fragmentManager = getSupportFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.fragment_container, fragment, activityType)
                        .commit();



            }catch (Exception e){
                Log.e("eEmp/StnFailAdapter","Excp due to"+e.toString());
            }
        }
    };
} 

但是它在getSupportFragmentManager();

处显示错误

When I click on item in the recyclerview, I need to navigate to fragment

1 个答案:

答案 0 :(得分:0)

getSupportFragmentManager()AppCompatActivity中的方法:https://developer.android.com/reference/android/support/v4/app/FragmentActivity#getSupportFragmentManager()

如果您使用支持库中的Fragment(扩展AppCompatActivity),则需要替换以下内容:

FragmentManager fragmentManager = ((Activity) context).getSupportFragmentManager();

或使用Android SDK中的片段:

FragmentManager fragmentManager = ((Activity) context).getFragmentManager();