刷新列表从MainActivity查看片段

时间:2014-01-25 07:36:23

标签: android android-fragments android-viewpager android-fragmentactivity fragmentpageradapter

很奇怪,很多人都问过这个问题但是没有一个有用的答案

我有一个MainActivity类

public class MainActivity extends FragmentActivity implements ActionBar.TabListener

有3个操作栏标签(第1,2,3节),每个部分在包

中都有自己的片段
public class FragmentA extends Fragment
public class FragmentB extends Fragment
public class FragmentC extends Fragment
在FragmentA中的

我有一个带有arraylist适配器的listView。

在MainActivity中

我获取一些数据并将其放在sqlite数据库中。

新数据添加到数据库后我想通知列表视图数据集已更改并填充新数据

这听起来很容易,但我真的被卡在了! 我只是想知道如何进行刷新,重建,重新创建......它是什么来自MainActivity

如果有人可以帮忙吗?感谢

3 个答案:

答案 0 :(得分:0)

最简单的方法是使用本地广播管理器。 developer.android.com/reference/android/support/v4/content/...您可以注册UI以接收广播,当数据保存在数据库中时可以触发该广播。当UI收到此事件时,您可以通知适配器刷新列表视图

答案 1 :(得分:0)

在您的活动中。

this.fragment.adapter.notifyDataSetChanged();

答案 2 :(得分:0)

鹤鹤。

这是个糟糕的主意吗?

public interface INotifyDataChange {
    public void notify(Object dataChanged); // Object stand for whatever you want. :">
}

您的主要活动

MainActivity {
    public static INotifyDataChange notifier;
    public void inSomeMethod() {
       // do input data.
       if (notifier != null) {
           notifier.notify(dataWillBeAttached);
       }
    }
}

你的片段:

FragmentA or B, or C implements INotifyDataChange {
    onCreateView() {
       MainActivity.notifier = this;
    }

    @Override
    public void notify(Object data) {
        Toast.make(..., "I've changed data " + data.toString(), ...).show();
        yourListView.notifyDataSetChanged(); // or anything like this.
    }

}