简体   繁体   English

在导航抽屉中加载具有不同参数的单个片段

[英]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 . 假设我有一个导航抽屉,其中包含三个菜单项,即cat1,cat2和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. 每当用户单击此按钮时,它将打开一个片段,该片段将从Web服务器中获取数据并解析JSON数据并显示在回收者视图中。

Now my question is. 现在我的问题是。 Do I need to create separate fragments for each menu item of navigation drawer ie cat1, cat2 and cat3 ? 我是否需要为导航抽屉的每个菜单项(即cat1,cat2和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? 或者,我可以使用一个片段,并将类似http://example.com?cat=1的参数传递给该片段,然后加载回收站视图项?

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. 在这种情况下,您仅应使用一个片段,这是通过对类别cat1,cat2,cat3仅使用一个片段来复用设计和代码的方法。 You can pass category id to the fragment via a bundle. 您可以通过捆绑包将类别ID传递给片段。 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. 如果您想在每次单击类别时获取数据,最好有一个片段并将其调用API。 But if you use three fragments, it reduces number of API calls in addition to faster switching between categories. 但是,如果使用三个片段,则除了可以更快地在类别之间切换之外,还可以减少API调用的次数。 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. 同样在第二种情况下,您应该关心每次更新从API获取的内容。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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