Android的 - 实例化一个片段多次吗? [英] Android - Instantiate a Fragment multiple times?

查看:94
本文介绍了Android的 - 实例化一个片段多次吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建在一个ListView显示数据的应用程序。数据分类中让说两种类型(流行,收藏夹)。我有一个活动和两个片段。所述片段显示基于其类别的项目的列表。我用一个ListView这一点。然后我有两个fragment_layouts这是完全一样的设计,但有不同的看法的id即tvId1,tvId2为TextViews。在codeS中的片段只在引用其相应的布局和视图中的布局不同。我从它是JSON格式的URL获取数据。但是,每个类别都有一套不同的URL产生相同结构只是不同的数据。然后我分析每个片段对应的URL并相应地填充的ListView。一切工作至今。

I'm creating an app that displays data in a ListView. Data is categorized in let say two types (Popular, Favorites). I have one Activity and two Fragments. The Fragments displays a list of items based on their category. I used a ListView for this. I then have two fragment_layouts which are exactly alike in design but have different view id's ie tvId1, tvId2 for TextViews. The codes in the Fragments only differ in referencing their corresponding layout and views in the layout. I get data from a URL which is in JSON format. But each category has a different set of URL which produces the same structure just different data. I then parse the corresponding URL on each Fragment and populate the ListView accordingly. Everything works so far.

我想知道,有没有我可以只使用一个片段,并与不同的组中的每个数据都使用它两倍的方法吗?这样,我就不必创建另一个片段,如果一个新的类别出现。

What I want to know, is there a way that I can just use one Fragment and use it two times with different set of data in each? This way I don't have to create another Fragment if a new category comes up.

鸭preciate任何帮助。

Appreciate any help.

推荐答案

当然,你可以做。事实上,你应该像这样做。

Of course you can do. In fact you should do it like this.

在创建的片段不使用新片段();
创建取数据作为参数静态的newInstance功能。

When you are creating the Fragment do not use new Fragment(); Create a static newInstance function that take the data as argument.

public static MyFragment newInstance(int type) {
    MyFragment fragment = new MyFragment();
    Bundle args = new Bundle();
    args.putInt("type", type);
    fragment.setArguments(args);
    return fragment;
}

然后你就可以使用下面获取类型的onCreate()方法:

And then you can get the type on onCreate() method using below:

getArguments().getInt("type");

和那么你得到的类型,可以相应地打电话给你的Web服务,然后可以设置查看相应。

And then you get the type, you can call your webservice accordingly, and then you can set the Views accordingly.

这篇关于Android的 - 实例化一个片段多次吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆