Android:在一个活动中更新同一个片段的两个实例

时间:2015-01-29 00:23:19

标签: android android-fragments android-listview

我有一个带有tabbar和两个片段的Activity。这些片段是同一片段类的不同实例。这两个片段碰巧都有一个列表视图。

在我的活动中的后台进程中加载​​新数据后,我想更新这两个片段中的两个列表视图。这基本上是我的更新代码:

// Code inside an AsynTask inside my MainActivity that gets called after I load some data from the server
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(MainActivity.this.fragment1);
ft.attach(MainActivity.this.fragment1);
ft.commit();

final FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
ft2.detach(MainActivity.this.fragment2);
ft2.attach(MainActivity.this.fragment2);
ft2.commit();

但是会发生这样的情况,这两个片段在此更新后显示相同的列表视图项目,并且它们始终显示上次更新片段的项目。

// onCreate method in my MainActivity
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //... initiation of action bar and sectionspager adapter here....

        // I create two different instances of "MyFragment" and I pass an integer (=status) to the constructor
        this.fragment1= new MyFragment(1);
        this.fragment2 = new MyFragment(2);
}

标题和列表视图项应该取决于构造函数中传递的整数。但只有两个片段的标题不同,而不是两个列表视图中的项目。

// inside the onCreate Method of my Fragment class
// Based on the passed integer I show a different title and I get a different list of items
if (status == 1)
    tvTitle.setText("Title 1");
} else if (status == 2){
    tvTitle.setText("Title 2");
}

ListView lv = (ListView) rootView.findViewById(R.id.fragment_list_view);

ArrayList<Joboffer> itemList = DataHolder.getInstance().getItemListForStatus(this.status);
lv.setAdapter(new ItemAdapter(getActivity(), itemList ));

我不确定我的问题有多普遍,但也许我错过了一些关于listviews如何工作的基本理解。两个listviews应该是不同的实例,在两个不同的片段内和两个不同的适配器。但有些人表示这没有用。

0 个答案:

没有答案
相关问题