2017-03-09 77 views
0

後,我有2個片段:FragmentAFragmentB。這兩個片段具有基本上看起來像這樣相同的代碼:Android的碎片恢復的TextView FragmentTransaction

public class FragmentB extends Fragment{ 

    private TextView textView; 
    private EditText editText; 
    private Button button; 

    boolean visible = true; 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState){ 
     final View rootView = inflater.inflate(R.layout.test_fragment, container, false); 

     if (textView != null) 
      Log.e("FragmentB", "Text was: " + textView.getText().toString()); 

     textView = (TextView) rootView.findViewById(R.id.textView); 
     editText = (EditText) rootView.findViewById(R.id.editText); 
     button = (Button) rootView.findViewById(R.id.button); 
     ((TextView)rootView.findViewById(R.id.fragment)).setText("Fragment B"); 

     button.setOnClickListener(new View.OnClickListener(){ 
      @Override 
      public void onClick(View v){ 
       Log.e("FragmentB", "Set text: " + editText.getText()); 
       textView.setText(editText.getText()); 
       visible = !visible; 
       textView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); 
      } 
     }); 

     Log.e("FragmentB", "Text now: " + textView.getText()); 

     return rootView; 
    } 
} 

到2個片段之間切換,我打電話​​其中currentFragment是當應用程序啓動時創建的同一個實例。問題是,每當我在FragmentB按下按鈕隱藏TextView,切換到FragmentA,然後回到FragmentB,TextView的是再次可見,但我還是想被隱藏。另外,如果我再來一次,TextView中的文本也會被重置,但是隻能在TWICE之前來回。

如何在切換它們時保持碎片的狀態?

我一直在使用onSaveInstanceState()onViewStateRestored()試過,但onViewStateRestored()不斷得到所謂與Bundle設置爲null。爲什麼會發生?

下面是代碼:

@Override 
public void onViewStateRestored(Bundle savedInstanceState){ 
    Log.e("FragmentB", "Bundle: " + savedInstanceState); 

    super.onViewStateRestored(savedInstanceState); 
    try{ 
     textView.setText(savedInstanceState.getString("text")); 
    }catch (NullPointerException e){ 
     e.printStackTrace(); 
    } 

    Log.e("FragmentB", "Bundle: " + savedInstanceState); 
    Log.e("FragmentB", "onViewStateRestored"); 
} 

@Override 
public void onSaveInstanceState(Bundle outState){ 
    super.onSaveInstanceState(outState); 
    outState.putString("text", textView.getText().toString()); 
    Log.e("FragmentB", "onSaveInstanceState"); 
} 

回答

0

使用replace會破壞其被替換片段。所以每次切換片段時,都會創建一個新片段。使用hideshow會對你更好。

fragmentTransaction.add(fragmentA).add(fragmentB).commit(); 
fragmentTransaction.show(fragmentA).hide(fragmentB).commit(); 
+0

這並不能解決問題,但如果片段當使用'替換()'被破壞,那麼爲什麼第二次顯示時,我的觀點不等於'null'。另外爲什麼'onDestroy()'不被調用? – TychoTheTaco

+0

因爲你重新創建了你的fragmentView和'findViewById'。將在被替換的片段中調用onDestroy(),而不是顯示片段。 – xiaoyuan

0

嘗試使用:的

fragmentTransaction.add(R.id.main_content_frame, currentFragment); 

代替:

fragmentTransaction.replace(R.id.main_content_frame, currentFragment);