Fragment
Fragment 是轻量级的,比Activity 快,适合同一个APP 内页面的跳转。
1: 在MainActivity 中启动一个fragment BlankFragment:
public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(savedInstanceState == null){ getSupportFragmentManager().beginTransaction() .add(R.id.container,new BlankFragment()) .commit(); } } @Override public void onFragmentInteraction(Uri uri) { } }
2、 在 BlankFragment 呈现一个按钮,点击按钮,转到另一个fragment:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main,container,false); rootView.findViewById(R.id.btnShowAnotherFragment).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getFragmentManager().beginTransaction() .addToBackStack(null) .replace(R.id.container, new AnotherFragment()).commit(); } }); return rootView; }
3、 在另一个fragment 增加一个返回按钮,返回到上一个fragment:
public class AnotherFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_another,container,false); root.findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { getFragmentManager().popBackStack(); } }); return root; } }
在第一个fragment A 跳转 到 第二个fragment B时:
执行 B.onCreate -- A.onPause -- A.onDestoryView --b.onCreateView , 在B页面点后退,执行 B.onPause -- B.onDestory