对方向变化保存碎片状态 [英] Saving Fragment State on Orientation Change

查看:126
本文介绍了对方向变化保存碎片状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我试图用一个新的替换当前ContentListFragment活动时重新对方向变化(code因为这是不低于),但应用程序的力量也关闭了NullPointerException异常在setFileDir(),因此,一切分崩离析。

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

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

 公共类ContentList扩展DrawerActivity实现ContentListFragment.listFragmentListener {

    //实例变量
    私人FragmentManager FM;
    私人FragmentTransaction英尺;
    私人字符串currentPath;

    //初始化变量。
    //如果活动开始首次,一个路径存储
    //接收。
    //否则,如果它是一个方向变化,路径只是保留。
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.content_list);

        如果(savedInstanceState == NULL){
            FM = getSupportFragmentManager();
            英尺= fm.beginTransaction();
            文件fil​​e = Environment.getExternalStorageDirectory();
            currentPath = file.getPath();
            ft.add(R.id.content_container_fragment_listview,新ContentListFragment());
            ft.commit();
        } 其他 {
            FM = getSupportFragmentManager();
            currentPath = savedInstanceState.getString(PATH);
        }
    }

    //返回的情况下取向的变化currentPath。
    @覆盖
    保护无效的onSaveInstanceState(包outState){
        super.onSaveInstanceState(outState);
        outState.putString(PATH,currentPath);
    }
 

dfsas

 公共类ContentListFragment扩展SherlockListFragment {

    //实例变量
    私人的ArrayList<项目>项目;
    私人的ArrayList<项目> copy_move_queue_items;
    私人ItemAdapter适配器;
    私人listFragmentListener lfListener;
    私人字符串currentPath;
    私人菜单项menuItemRename;

    //实例化使用setFileDir()变量和从容器的活动的路径。
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        setRetainInstance(真正的);
        currentPath =((ContentList)getActivity())getCurrentPath()。
        setFileDir(currentPath);

    }

    //获取一个到活动界面
    @覆盖
    公共无效onAttach(活动活动){
        super.onAttach(活动);
        尝试 {
            lfListener =(listFragmentListener)的活动;
        }赶上(ClassCastException异常E){
            抛出新ClassCastException异常(activity.toString()
                    +必须实现listFragmentListener);
        }
    }

    //设置列表视图和动作条的UI
    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
                             捆绑savedInstanceState){

        视图V = inflater.inflate(R.layout.content_list_fragment,集装箱,假);

        文件fil​​e = Environment.getExternalStorageDirectory();
        串ROOTPATH​​ = file.getPath();

        //设置操作栏标题当前目录下,并创建一个向上
        //启示如果根路径不等于当前路径
        。getSherlockActivity()getSupportActionBar()的setTitle(空)。
        。getSherlockActivity()getSupportActionBar()setLogo(R.drawable.ab_icon)。

        如果(currentPath.equals(ROOTPATH​​)){
            getSherlockActivity()。getSupportActionBar()
                    .setDisplayHomeAsUpEnabled(假);
            getSherlockActivity()。getSupportActionBar()
                    .setHomeButtonEnabled(假);
        } 其他 {
            getSherlockActivity()。getSupportActionBar()
                    .setDisplayHomeAsUpEnabled(真正的);



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

        返回伏;

    }

    //设置长按上下文操作模式到ListView
    @覆盖
    公共无效onActivityCreated(包savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        setActionMode();
        setListAdapter(适配器);
    }
    //获取文件的列表中的路径,并将它们添加到项目的ArrayList,
//初始化适配器以及
公共无效setFileDir(字符串路径){
    档案文件=新的文件(路径);
    文件[]文件= file.listFiles();
    Arrays.sort(文件,新fileComparator());
    项目=新的ArrayList<项目>();
    对于(F文件:文件){
        items.add(新项目(F));
    }
    适配器=新ItemAdapter(getActivity(),R.layout.content_list_item,项目);
}
 

解决方案

使用此为节省取向片段的状态。

 的onCreate(包保存)
{
   super.onCreate(保存);
   setRetainInstance(真正的);
}
 

I'm creating a file manager app for Android, and two classes below are the majority of the logic that goes into doing that. What I'm doing is that on startup of the ContentList, it adds the ContentListFragment to the container layout in the ContestList xml. By adding the ContentListFragment, I get the current path, then call setFileDir(String S) that basically gets the File at the passed in path, getting the list of Files at that location, initializing the array, and then initializing the adapter. I then set the Adapter, set the Action Bar UI, and the contextual Action Bar. Now, each time a item on the ContentListFragment is pressed, it creates another ContentListFragment, using the path of the selected item. The fragment before is then added to the back stack. Now that's all fine and dandy, the problem comes though when orientation occurs.

That setRetainInstance(true) in the onCreate of ContentListFragment is the only thing thats keeping the whole app from force closing when the app changes orientation. However, doing it this way cause the app to force close later when I return to it after a while (which is the main problem I'm having, and can't understand why).

I tried to replace the current ContentListFragment with a new one when the Activity is recreated on orientation change (code for this is not below), but the app force closes also with a NullPointerException at setFileDir(), and therefore everything else falls apart.

How do I save the fragment state so that on orientation change everything stays the same as it did before the orientation change, and without it force closing later when I return to it after a while?

Just in case, my app is just one Activity with recursive 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);
}

解决方案

use this for save state of fragment on orientation.

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

这篇关于对方向变化保存碎片状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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