luwach
luwach

Reputation: 225

Fragment transaction after clicking item in RecyclerView

Here is my problem. I want to make fragment transaction when I click a single item in my RecyclerView. In pager adapter, I created rootListFragment which is a container for other Fragments. When rootListFragment is created it contains my fragment with RecyclerView which I named ListFragment. When I click single item I want to replace rootListFragment to WebViewFragment which contains for now only single text "Hello blank fragment". After this transaction, my ListFragment is still in front view. Do you know how to solve this problem? Here's my code.

RootListFragment:

public class RootListFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_root_list, container, false);

        FragmentManager fragmentManager = getChildFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.root_list_fragment, new ListFragment()).commit();

        return view;
    }

}

Part of RecyclerView with item click

public static class DataViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        ...

        public DataViewHolder(View view) {
            super(view);

            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {

            AppCompatActivity activity = (AppCompatActivity) v.getContext();
            activity.getSupportFragmentManager().beginTransaction().replace(R.id.root_list_fragment, new WebViewFragment())
                    .commit();
        }
    }
}

Screen of app after item click: screen

Upvotes: 1

Views: 1194

Answers (1)

Sandeep dhiman
Sandeep dhiman

Reputation: 1921

I think problem is in your onclick method get your Context/activity value in your Adapter Constructor like this

   public ViewAdapter(Context context, List<Information> data)
{
    inflater=LayoutInflater.from(context);
    this.data=data;
    this.context=context;

}

and then in your onclick method put below code

context.getSupportFragmentManager().beginTransaction().replace(R.id.root_list_fragment, new WebViewFragment())
                .commit();

Upvotes: 1

Related Questions