Android 碎片(Fragment)基础全解析
1. 碎片事务(FragmentTransactions)与碎片返回栈(Fragment Back Stack)
当 showDetails()
方法引入新的详细碎片时,虽然代码看似简单,但背后有很多操作。若活动处于多窗格模式,要在标题列表旁的碎片中显示详细信息。可以通过资源 ID R.id.details
来判断布局中是否已有详细碎片,使用 findFragmentById()
方法向碎片管理器查询,若帧布局为空则返回 null
,否则返回当前详细碎片。
下面是一个碎片事务的示例代码:
public void showDetails(int index) {
Log.v(TAG, "in MainActivity showDetails(" + index + ")");
if (isMultiPane()) {
// Check what fragment is shown, replace if needed.
DetailsFragment details = (DetailsFragment)
getFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Mak