如何通过代码设置Fragment标签?

Axe*_*cia 135 android android-fragments android-3.0-honeycomb

我没有setTag(String tagName)Fragment课堂上找到类似方法的东西.设置Fragment我找到的标记的唯一方法是执行a FragmentTransaction并将标记名称作为参数传递.

这是Fragment通过代码显式设置标记的唯一方法吗?

PJL*_*PJL 114

是.所以唯一的办法就是在交易时间,例如使用add,replace或作为布局的一部分.

我通过检查兼容性来源确定了这一点,因为我在过去的某些时候曾简要地查找类似内容.

  • 你的答案在[here] [1]在stackoverflow上的帖子[1]:http://stackoverflow.com/questions/9363072/android-set-fragment-id (2认同)
  • 使用FragmentTransaction的add(int containerViewId,Fragment fragment,String tag)如下所述:http://stackoverflow.com/a/13244471/4002895 @PJL请编辑你的答案.这个答案误导人们 (2认同)

Dav*_*vid 69

您可以通过以下方式将标记设置为片段:

Fragment fragmentA = new FragmentA();
getFragmentManager().beginTransaction()
    .replace(R.id.MainFrameLayout,fragmentA,"YOUR_TARGET_FRAGMENT_TAG")
    .addToBackStack("YOUR_SOURCE_FRAGMENT_TAG").commit(); 
Run Code Online (Sandbox Code Playgroud)

  • 我在哪里用这个代码?在FragmentPagerAdapter中的getItem中? (6认同)

小智 34

您可以在活动布局xml文件中提供标记.

"为android:tag属性提供唯一的字符串."

就像在布局xml中分配id一样.

    android:tag="unique_tag"
Run Code Online (Sandbox Code Playgroud)

链接到开发者指南

  • 如果使用布局文件,那将会有效.但是这个问题涉及在Java中动态设置标记. (30认同)