2016-03-16 47 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。您只需啓動活動或替換片段。 –