对取向变化保存碎片状态(Saving Fragment State on Orientation C

2019-07-17 11:51发布

我创建一个文件管理器应用程序的Android和下面两个类是大部分是进入这样做的逻辑。 我在做什么是对ContentList启动时,它会将ContentListFragment在ContestList XML的容器布局。 通过添加ContentListFragment,我得到的电流路径,然后调用setFileDir(String s)将基本上得到文件在路径传递,获取文件列表在该位置,初始化数组,然后初始化适配器。 然后我适配器设置,设置操作栏UI,和上下文操作栏。 现在,每个被按压在ContentListFragment一个项时,它创建另一个ContentListFragment,使用所选择的项的路径。 的片段之前被加入到背面堆栈。 现在,一切都很好,很正常,问题就来了,虽然当朝向发生。

在ContentListFragment的OnCreate那setRetainInstance(真)是多数民众赞成由强制关闭保持整个应用程序时,应用程序改变方向的唯一的事情。 但是,做这种方式导致应用程序后,以强制关闭,当我回到它一段时间后(这是我遇到的主要问题,并不能明白为什么)。

我试图与当活动是方向改变重新创建一个新的替换当前ContentListFragment(此代码不低于),但应用力还与一个NullPointerException关闭在setFileDir(),因此一切分崩离析。

如何保存碎片状态,以便与方向改变一切保持不变,因为它的方向改变之前一样,没有它强制关闭后,当我一段时间后返回到它?

为以防万一,我的应用程序只是一个活动递归ContentListFragments。

public class ContentList extends DrawerActivity implements ContentListFragment.listFragmentListener{

    // instance variables
    private FragmentManager fm;
    private FragmentTransaction ft;
    private String currentPath;

    // Initializes variables.
    // If Activity is started for the first time, a path to the storage is
    // received.
    // Else, if it's an orientation change, the path is just retained.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_list);

        if (savedInstanceState == null) {
            fm = getSupportFragmentManager();
            ft = fm.beginTransaction();
            File file = Environment.getExternalStorageDirectory();
            currentPath = file.getPath();
            ft.add(R.id.content_container_fragment_listview, new ContentListFragment());
            ft.commit();
        } else {
            fm = getSupportFragmentManager();
            currentPath = savedInstanceState.getString("PATH");
        }
    }

    // Grabs the currentPath in case of orientation changes.
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("PATH", currentPath);
    }

dfsas

public class ContentListFragment extends SherlockListFragment {

    // instance variables
    private ArrayList<Item> items;
    private ArrayList<Item> copy_move_queue_items;
    private ItemAdapter adapter;
    private listFragmentListener lfListener;
    private String currentPath;
    private MenuItem menuItemRename;

    // instantiates variables using setFileDir() and the path from the container Activity.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        currentPath = ((ContentList) getActivity()).getCurrentPath();
        setFileDir(currentPath);

    }

    // Gets a reference to Activity interface
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            lfListener = (listFragmentListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + "must implement listFragmentListener");
        }
    }

    // Sets the UI of the listView and the ActionBar
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.content_list_fragment, container, false);

        File file = Environment.getExternalStorageDirectory();
        String rootPath = file.getPath();

        // Sets Action Bar title to current directory, and creates an Up
        // affordance if the root path doesn't equal the current Path
        getSherlockActivity().getSupportActionBar().setTitle(null);
        getSherlockActivity().getSupportActionBar().setLogo(R.drawable.ab_icon);

        if (currentPath.equals(rootPath)) {
            getSherlockActivity().getSupportActionBar()
                    .setDisplayHomeAsUpEnabled(false);
            getSherlockActivity().getSupportActionBar()
                    .setHomeButtonEnabled(false);
        } else {
            getSherlockActivity().getSupportActionBar()
                    .setDisplayHomeAsUpEnabled(true);



            // getSherlockActivity().getSupportActionBar().setTitle("/" +
            // (currentPath.substring(currentPath.lastIndexOf("/") +1)));
        }

        return v;

    }

    // Sets the long click Contextual Action Mode to the ListView
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setActionMode();
        setListAdapter(adapter);
    }
    // Gets the list of files at the path and adds them to the Item ArrayList,
// initializing the adapter as well
public void setFileDir(String path) {
    File file = new File(path);
    File[] files = file.listFiles();
    Arrays.sort(files, new fileComparator());
    items = new ArrayList<Item>();
    for (File f : files) {
        items.add(new Item(f));
    }
    adapter = new ItemAdapter(getActivity(), R.layout.content_list_item, items);
}

Answer 1:

用这个节省取向片段的状态。

onCreate(Bundle save)
{
   super.onCreate(save);
   setRetainInstance(true);
}


Answer 2:

这个工作对我来说

@Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        onCreate(savedInstanceState);
    }

并在活动标签内的清单文件

android:configChanges="orientation|screenSize"



Answer 3:

刚发布此,因为这是面临的一个重大关切工作和它被废弃了(此方法是涉及到这是目前移动到片段活动),现在我们有一个新的采访:) API 13前,我们使用onRetainNonConfigurationInstance()方法知道作为setRetainInstance()(片段类的方法部分),这将甚至活性创建后保存片段的状态。



文章来源: Saving Fragment State on Orientation Change