getFragmentManager().beginTransaction() .addToBackStack(null) .replace(R.id.container, fragment) // 也可用.add(),差在原Fragment會不會觸發destory .commit();
2.按下返回鍵會回到上一個Fragment
// 切換Fragment時,記得加上這個 .addToBackStack(null)
// 在Activity中加入以下程式碼 @Override public void onBackPressed() { FragmentManager fm = this.getFragmentManager(); if (fm.getBackStackEntryCount() == 0) { this.finish(); } else { fm.popBackStack(); } }
3.Fragment間溝通
public FragmentA extends Fragment { private void goToFragmentB() { Fragment fragment = new FragmentB(); // 記得加上這句,讓FragmentB知道溝通的對象 fragment.setTargetFragment(this, 0); getFragmentManager() .beginTransaction() .add(R.id.container, fragment) .addToBackStack(null) .commit(); } // 實作介面 @Override public void doSomething() { // do something. } }
public FragmentB extends Fragment implement Listener { private Listener mListener; // 定義溝通的介面 public interface Listener() { public void doSomething(); } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mListener= (Listener) getTargetFragment(); } private void timeToDoSomething() { mListener.doSomething(); } }