0

我一直在查看 android 文档和网络上的各种资源,但我似乎无法让我的应用程序在重新创建活动时保留数据(比如按下后退按钮退出然后从图标进入应用程序或任务管理器)。

我有3个类:主要的(扩展FragmentActivity),一个片段和一个在应用程序不活动时应该在后台运行的类,在创建活动后,它需要更新片段。

以下是我的消息来源:

主要的

public class Main extends FragmentActivity {

    private FragmentExample mFragment;
    private BackgroundClass bgClass = new BackgroundClass();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        manageFragment(getSupportFragmentManager());
    }

    protected void manageFragment(FragmentManager fm) {

        mFragment = (FragmentExample) fm.findFragmentByTag("TAG");

        if (mFragment == null) {
            mFragment = new mFragment();
            fm.beginTransaction().add(mFragment,"TAG").commit();
        }

        else fm.beginTransaction().attach(mFragment).commit();
    }


    @Override
    protected void onStart() {
        super.onStart();
        mFragment = bgClass.update(mFragment);
    }
}

分段

public class FragmentExample extends Fragment {

    //declare variables

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);

        //initialize variables from View

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //more initializations
    }
}

背景类

public class BackgroundClass extends SomeOtherClass {

    //declare variables

    protected FragmentExample update(final FragmentExample fExample) {
        //update listeners, variables, etc
        return fExample;
    }

//Overridden methods from SomeOtherClass

}

目前它仅在我更改配置(即旋转屏幕)时更新数据。任何形式的帮助都会很棒。

4

0 回答 0