简体   繁体   中英

Load a single Fragment with different arguments in navigation drawer

Suppose I have a navigation drawer which contains three menu item ie cat1, cat2, and cat3 . Whenever a user clicks on this it will open a Fragment which will fetch the data from the web server and parse the JSON data and show into recycler view.

Now my question is. Do I need to create separate fragments for each menu item of navigation drawer ie cat1, cat2 and cat3 ? Or I can use one fragment and pass an argument like this http://example.com?cat=1 to that fragment and load the recycler view item?

So which procedure should I follow to achieve this goal, separate fragment for each menu item or a single fragment? Thanks.

You should use only one fragment in this case this is how you can reuse design and code by using just one fragment for each category cat1, cat2, cat3. You can pass category id to the fragment via a bundle. check this tutorial

If you want to fetch data every time you click on a category, it's better to have one fragment and make it call the API. But if you use three fragments, it reduces number of API calls in addition to faster switching between categories. However, there is a trade-off between them. Also in second case, you should care about updating contents that is fetched from API every time.

You should definitely use a single fragment and avoid some boilerplate code. Here is a how you should do it:

public class CategoryFragment extends Fragment {
    public static CategoryFragment newInstance(int categoryId) {
        CategoryFragment fragment = new CategoryFragment();
        Bundle extras = new Bundle();
        extras.putInt("categoryId", categoryId);
        fragment.setArguments(extras);
        return fragment;
    }
    ...
    // Determine which category you're on
    private int getCategoryId() {
        return getArguments().getIntExtra("categoryId", 1);
    }
}

And to instantiate your fragment you can simply use:

// Construct a cat2 fragment
CategoryFragment categoryFragment = CategoryFragment.newInstance(2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM