方向更改时,片段视图为空

时间:2013-02-17 02:42:22

标签: android view android-fragments

在将我的应用从正常活动样式移植到片段样式时,我遇到了一些问题。我开始注意到,当一个片段被重新创建,或者从后台堆栈中弹出时,它会丢失它的视图。当我说我特别谈论列表视图时。我正在做的是将项目加载到列表视图中,然后旋转屏幕。当它返回时,它会得到一个nullpointerexception。我调试它,果然listview为null。这是片段的相关代码

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.sg_question_frag, viewGroup, false);

    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        list = (ListView)getActivity().findViewById(R.id.sgQuestionsList);
        if (savedInstanceState != null) {
            catId = savedInstanceState.getInt("catId");
            catTitle = savedInstanceState.getString("catTitle");
        }
        populateList(catId, catTitle);
    }

以下是它的调用方式(请记住,还有一些其他片段也可以使用)

@Override
    public void onTopicSelected(int id, String catTitle) {
        // TODO Auto-generated method stub
        FragmentManager fm = this.getSupportFragmentManager();

        SGQuestionFragment sgQuestFrag = (SGQuestionFragment) fm.findFragmentByTag("SgQuestionList");
        FragmentTransaction ft = fm.beginTransaction();
        //If the fragment isnt instantiated
        if (sgQuestFrag == null) {

            sgQuestFrag = new SGQuestionFragment();
            sgQuestFrag.catId = id;
            sgQuestFrag.catTitle = catTitle;
            //Fragment isnt there, so we have to put it there

            if (mDualPane) {
                //TO-DO
                //If we are not in dual pane view, then add the fragment to the second container
                ft.add(R.id.sgQuestionContainer, sgQuestFrag,"SgQuestionList").commit();

            } else {
                ft.replace(R.id.singlePaneStudyGuide, sgQuestFrag, "SqQuestionList").addToBackStack(null).commit();
            }
        } else if (sgQuestFrag != null) {
            if (sgQuestFrag.isVisible()) {
                sgQuestFrag.updateList(id, catTitle);
            } else {
                sgQuestFrag.catId = id;
                sgQuestFrag.catTitle = catTitle;
                ft.replace(R.id.sgQuestionContainer, sgQuestFrag, "SgQuestionList");
                ft.addToBackStack(null);
                ft.commit();
                sgQuestFrag.updateList(id, catTitle);

            }
        }
        fm.executePendingTransactions();
    }

我最终希望它做的是完全重新创建活动,忘记碎片和所有内容,就像在横向模式或纵向模式下启动活动一样。我真的不需要那里的片段,我可以用一些保存的变量重新创建它们

1 个答案:

答案 0 :(得分:3)

如果您希望从Fragment中获取对视图的引用,请始终在View方法返回的View中查找getView()。在您的情况下,当您查找ListView时,Fragment的视图可能尚未附加到活动,因此引用将为null。所以你使用:

list = (ListView) getView().findViewById(R.id.sgQuestionsList);