如何更新在另一个片段的Lis​​tView? [英] How do I update ListView in another Fragment?

查看:210
本文介绍了如何更新在另一个片段的Lis​​tView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有持有 ViewPager 2个片段的活动。一个片段是将项目添加到的ListView 和另一个片段控股的ListView

I have an Activity which holds a ViewPager with 2 Fragments. One fragment is for adding items to ListView and another fragment is holding the ListView.

我一直在努力,现在快3天没有任何积极的结果。如何更新另一个片段的的ListView 从第一个片段?

I've been trying for almost 3 days now without any positive results. How do I update the other fragment's ListView from the first fragment?

我试图调用更新的ListView 从持有活动 ViewPager ,但它不'的方法将不起作用。

I'm trying to call the method that updates ListView from the Activity that holds ViewPager but it doesn't work.

从调用 ViewPager 方法的活动

@Override
    public void onPageSelected(int position) {
    library.populateListView(getApplicationContext());
    aBar.setSelectedNavigationItem(position);
}

这是 populateListView 方法:

public void populateListView(Context context){      
    CustomListViewAdapter customAdapter = new CustomListViewAdapter(getDatabaseArrayList(context), getActivity());

        if (lView != null)
        {
            lView.setAdapter(customAdapter);
        }
        customAdapter.notifyDataSetChanged();
}

然而,这不起作用,因为因为这个时候被调用的那一刻没有显示片段LVIEW变量(ListView控件)为null。

However this doesn't work because the lView variable (ListView) is null because the fragment isn't shown at the moment when this is being called.

推荐答案

我假设功能populateListView()是含片段在ListView的功能。您在每次调用使用onPageSelected调用populateListView()。如果你没有检查什么是被选择的位置。反正populateListView()方法应该是片段Containg的ListView的公共方法。您可以从实例化的Viewpager适配器片段在活动,比调用此方法。以这种方式在ListView不能为空。

I am assuming that function populateListView() is a function of the Fragment Containing the ListView. You are Calling populateListView() on every Call to onPageSelected. Should you not check what is the position that is being selected. Anyway The populateListView() Method should be a public method of the Fragment Containg ListView. And You Can Instantiate The Fragment from the Viewpager Adapter in the Activity and than call this method. In That way the listView should not be null.

@Override
public void onPageSelected(int position) {
ListViewFragment frag=(ListViewFragment)adapter.instantiateItem(viewPager, 1);
//here adapter is the ViewPager Adapter and you must supply the viewpager that    contains 
//the fragments and also the position of the fragment to instantiate. 
//For example 0 or 1 etc.
frag.populateListView(getApplicationContext());
aBar.setSelectedNavigationItem(position);
}

这篇关于如何更新在另一个片段的Lis​​tView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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