如何回到之前的片段rootview

时间:2016-03-16 07:43:51

标签: android android-fragments

我有两种布局 layout1 layout2

最初在我的片段的onCreateView中,我使用的是layout1:

    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            rootView = inflater.inflate(R.layout.layout1, container, false);

            Button button = (Button) rootView.findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setViewLayout(R.layout.layout2);
            }
        });


            return rootView;
    }

在那个onclick按钮后,我正在从 layout1 更改 layout2 两个 layout2 ,并且工作正常:

这就是我改变的方式:

private void setViewLayout(int id){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rootView = inflater.inflate(id, null);
        ViewGroup viewGroup = (ViewGroup) getView();
        viewGroup.removeAllViews();
        viewGroup.addView(rootView);
    }

要访问 layout2 的字段,我创建了一个类并在按钮的onClick事件上实例化它:

现在我想从 layout2 返回 layout1 我做了同样的事情并且视图正在改变但字段不能正常工作,就像layout1的onClick按钮现在没有响应。

PS:我不想再次开始片段,我只想要我以前的layout1而不是新的。

我怎样才能返回,以便我可以使用以前的 layout1 状态?

3 个答案:

答案 0 :(得分:1)

这里更好的方法是为每个布局使用两个单独的片段,然后单击用第二个替换当前片段。

您已经无法恢复以前的布局,因为您已从rootview中删除了

其次你没有保存片段状态

答案 1 :(得分:0)

这不是它的完成方式。您需要在backstack中添加片段以维持状态。从android开发者网站查看implement back navigation for fragments。希望它有所帮助。

答案 2 :(得分:0)

您可以尝试替换片段。不是setViewLayout(R.layout.layout2)