2

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

@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();
    }

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

4

1 回答 1

4

Fragment如果你想从一个总是View在方法View返回的视图中获取一个视图的引用getView()。在您的情况下,在您查找'ListViewFragment视图时可能尚未附加到活动,因此引用将为空。所以你使用:

list = (ListView) getView().findViewById(R.id.sgQuestionsList);
于 2013-02-18T05:17:09.620 回答