Search code examples
androidandroid-viewpagerandroid-listfragmentmaster-detail

Creating master/detail flow with ViewPager


How can I use the master detail flow inside a tabbed activity?

I have a view pager that has 3 pages. I'm trying to use the master/detail flow provided by android studio as one of the fragments in the view pager.


Solution

  • You can try doing this:

    1. Change the extends from Activity to Fragment.
    2. Add the method onCreateView and move everything from onCreate there except super.onCreate() and setContentView():

      @Override
      
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          FragmentActivity faActivity  = (FragmentActivity)    super.getActivity();
          // Replace LinearLayout by the type of the root element of the layout you're trying to load
          LinearLayout        llLayout    = (LinearLayout)    inflater.inflate(R.layout.activity_layout, container, false);
          // Of course you will want to faActivity and llLayout in the class and not this method to access them in the rest of
          // the class, just initialize them here
      

      // Content of previous onCreate() here // ...

      // Don't use this method, it's handled by inflater.inflate() above :
      // setContentView(R.layout.activity_layout);
      
      // The FragmentActivity doesn't contain the layout directly so we must use our instance of     LinearLayout :
      llLayout.findViewById(R.id.someGuiElement);
      // Instead of :
      // findViewById(R.id.someGuiElement);
      return llLayout; // We must return the loaded Layout
      

      }

    3. Remove method onCreate.

    4. Everywhere you access the Activity with this.something or just something replace with super.getActivity(). or use the value saved in the onCreateView like shown in 2). Example : Intent i = getIntent(); become Intent i = super.getActivity().getIntent()