start Fragment from RecycleView Adapter Onclick

安稳与你 提交于 2019-12-23 04:26:49

问题


Hi I have A RecycleView Adapter and A button. I want that button to start a Fragment. I can start an activity but not a fragment. I have tried this Onclick method for my Button

@Override
        public void onClick(View v) {
            Bundle bundle = new Bundle();
            bundle.putParcelable("event", events.get(getLayoutPosition()));
            Fragment fragment = new EditEventDetailFragment();
            fragment.setArguments(bundle);
            fragment.getFragmentManager().beginTransaction().replace(R.id.contentMainDrawer,fragment).commit();
        }

But have error invoke null object (contentMainDrawer) is my Main activity content_layout.

Any help is much appreciate. The Fragment host recycle view is call from Mainactivity


回答1:


Use below code for replace fragment

 Fragment fragment = new EditEventDetailFragment();
 FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
 FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
 fragmentTransaction.replace(R.id.contentMainDrawer, fragment, "tag").commit();

if you are using this code inside adapter than replace getActivity() to ((Activity) context).




回答2:


Hi I have found 2 answer that help whoever needed. The answer is to use the Activity that host the calling fragment. Many thanks @Mohit Suthar

Bundle bundle = new Bundle();
            bundle.putParcelable("event", events.get(getLayoutPosition()));
            Fragment fragment = new EditEventDetailFragment();
            fragment.setArguments(bundle);

            FragmentManager fragmentManager = ((MainActivity) context).getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.contentMainDrawer, fragment, "tag").commit();


来源:https://stackoverflow.com/questions/34527115/start-fragment-from-recycleview-adapter-onclick

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