来自ApiDemos样本的FragmentLayout类中的Strange FragmentTransaction

ilo*_*mbo 7 android sample android-fragments fragmenttransaction

对不起,这个问题适用于那些使用Eclipse访问ApiDemo示例代码的人.
具体来说,我试图将片段活动基于名为FragmentLayout的样本

以下代码对我来说有问题(您可以在ApiDemo FragmentLayout.java,ShowDetails()方法中找到完整代码):

                // Execute a transaction, replacing any existing fragment
                // with this one inside the frame.
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                if (index == 0) {
                    ft.replace(R.id.details, details);
                } else {
                    ft.replace(R.id.a_item, details);
                }
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
Run Code Online (Sandbox Code Playgroud)

我有两个问题:

  1. index == 0和之间有什么区别index != 0

  2. 资源R.id_a_item(在搜索之后仅在所有ApiDemos中出现)属于某种菜单快捷方式资源,根本不清楚为什么在这里使用它.

android.developers指南没有解释这段代码.

Luk*_*rog 4

index == 0 和 index != 0 有什么区别?

列表的位置和其他位置之间不应该有任何差异0,因为代码设置为简单地将先前的详细信息片段替换为新的详细信息片段。

资源R.id_a_item(仅在所有ApiDemo中出现,搜索后)属于某种菜单快捷方式资源,完全不清楚为什么在这里使用它。

最有可能的是示例中的一个错误,因为使用该 id 会引发异常,因为它在当前布局中不存在(我已经运行了API Demos在 4.2 模拟器上找到的项目,它引发了no view found 异常...等等)。可能是示例的最后一个版本中出现了错误,因为您质疑的代码片段在其他版本中不存在。

  • 是的,我就是这么想的。但你永远不会知道 Android 系统,根据墨菲定律,如果我不问这个问题,结果会是 `if(index==0)` 东西会挂起应用程序或删除内部 RAM :-) (2认同)