在不同活动或碎片之间共享数据的正确方法是什么?

Jit*_*ary 5 android listview gridview android-fragments android-viewpager

我需要一个应该具有UI工作流的应用程序,其中用户应该能够浏览应用程序的特定部分,该部分可以是ListView或GridView,并且他可以点击某个项目以显示该特定项目的详细信息.现在,如果用户向右滑动"即ViewPager",则View寻呼机应更改片段以显示上一个列表中的下一个或上一个项目,具体取决于用户滑动的方向,当用户按下详细信息时项目视图应该关闭现有的ViewPager,并且应该显示先前的ListView或GridView,并且应该将View的位置设置为用户在ViewPager中查看的项目.

为了保持简单和高效,两个视图,即ListView和Approach应该读取和写入相同的数据结构,它们应该是同步的,这样当在一个屏幕上启动加载更多数据时,同时如果用户选择了特定项目下一个视图应该在上一个屏幕加载完成后自动更新数据.

在此输入图像描述

就像Fancy9gag一样

编辑:我不想维护数据库,我只需要访问数据,直到我的应用程序的进程存活.

Tec*_*ift 0

Android 使用 Bundle 提供从 String 值到各种 Parcelable 类型的映射。

对于活动:-

Intent in = new Intent(Sender.this, Receiver.class); 
in.putString(key, value)
startActivity(in);
Run Code Online (Sandbox Code Playgroud)

对于片段使用捆绑包:-

Fragment fragment = new Fragment(); 
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
Run Code Online (Sandbox Code Playgroud)

针对您的场景进行编辑:我认为更好的选择是创建应用程序池。

请按照以下步骤操作:- 启动应用程序池:-

ApplicationPool pool = ApplicationPool.getInstance();
Run Code Online (Sandbox Code Playgroud)

详情页修改数据并添加到池中

pool.put("key", object);
Run Code Online (Sandbox Code Playgroud)

从池中获取列表页修改后的数据

Object  object = (Object) pool.get("key");
Run Code Online (Sandbox Code Playgroud)

重要提示:- 获取数据后通知listview或gridview

应用程序池类文件

public class ApplicationPool {

    private static ApplicationPool instance;
    private HashMap<String, Object> pool;

    private ApplicationPool() {
        pool = new HashMap<String, Object>();
    }

    public static ApplicationPool getInstance() {

        if (instance == null) {
            instance = new ApplicationPool();

        }

        return instance;
    }

    public void clearCollectionPool() {
        pool.clear();
    }

    public void put(String key, Object value) {
        pool.put(key, value);
    }

    public Object get(String key) {
        return pool.get(key);
    }

    public void removeObject(String key) {

        if ((pool.get(key)) != null)
            pool.remove(key);

    }
}
Run Code Online (Sandbox Code Playgroud)