Android - 设置片段ID

tyb*_*tyb 109 android android-fragments

我如何可以设置FragmentId,这样我可以使用getSupportFragmentManager().findFragmentById(R.id.--)

Tho*_*nan 112

您无法以编程方式设置片段的ID.

但是,String tag您可以在FragmentTransaction中设置一个可用于唯一标识片段的片段.

正如阿列克谢指出的那样,你可以通过一个ID FragmentTransactionadd(int, Fragment)方法.但是,这不指定片段的ID.它指定ViewGroup要插入的a的ID Fragment.这对我预期的目的没有用,因为它没有唯一标识Fragments,而是ViewGroups.这些ID是容器,可以动态添加一个或多个片段.使用这样的方法来识别Fragments将需要您ViewGroup为每次Fragment插入时动态添加s .那将是非常麻烦的.

所以,如果你的问题是如何为你动态添加片段的唯一标识符,答案是使用FragmentTransaction添加(INT containerViewId,片段片段,字符串标记) 的方法和FragmentManagerfindFragmentByTag(字符串)方法.

在我的一个应用程序中,我被迫动态生成字符串.但无论如何,相对于实际的FragmentTransaction而言,它并不昂贵.

标记方法的另一个优点是它可以识别未添加到UI的片段.请参阅FragmentTransaction的add(Fragment,String)方法.Fragment不需要Views!它们还可用于在配置更改之间保持短暂状态!

  • @TomDignan将如何在ViewPager中添加片段?我该如何设置他的标签?我不能在这种情况下使用交易. (11认同)
  • 可以稍微编辑一下答案以强调您可以在 xml 布局中设置 id 吗?因为我个人没有阅读其他问题,并且印象中根本没有办法为片段设置 id... (2认同)

Moo*_*als 40

事实证明,您可能不需要知道片段ID.

来自文档:

public abstract Fragment findFragmentById (int id)

Finds a fragment that was identified by the given id either
when inflated from XML or as the container ID when added in
a transaction.
Run Code Online (Sandbox Code Playgroud)

重要的部分是"作为事务中添加的容器ID".

所以:

getSupportFragmentManager()
    .beginTransaction()
    .add(R.id.fragment_holder, new AwesomeFragment())
    .commit();
Run Code Online (Sandbox Code Playgroud)

然后

AwesomeFragment awesome = (AwesomeFragment)
     getSupportFragmentManager()
          .findFragmentById(R.id.fragment_holder);
Run Code Online (Sandbox Code Playgroud)

会得到你在R.id.fragment_holder中保存的任何(真棒)片段.