2016-03-16 50 views
3

的上一个rootview我有两个布局layout1layout2如何返回到片段

在onCreateView

最初我的片段,我使用布局1所示:

@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按钮后我从布局1 布局2改变rootView其做工精细:

这就是我正在改变的方式:

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

要访问领域布局2的我创建一个类实例化它的按钮的onClick事件:

现在我想回去布局1布局2我做相同的,观点正在改变,但字段不像layout1的onClick按钮现在没有响应。 PS:我不想再次开始片段,我只想要我以前的layout1而不是新的。

我该怎么回去,以便我可以使用我以前的状态layout1

回答

1

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

,你将无法恢复以前的布局,你已删除从rootview

其次,你是不是节省片段状态

0

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

+0

已经提到,我不想开始新的片段。 – Spartan

+0

您无法在onClickListener上设置ViewLayout。您只需启动活动或替换片段。 –