【发布时间】:2016-06-20 06:33:39
【问题描述】:
每当我在 Fragment 类的“OnCreateView”中调用 inflate 方法时,我都希望获得一个具有 android:id 值中指定的 ID 的片段。 但我得到了一个不同的 id,与 containerID 相同。
我正在尝试以编程方式在 relativeLayout 中添加片段,对于此处显示的示例,我有两个片段,其中一个必须设置 RelativeLayout.BELOW 参数。
这是顶部片段 (ts_fragment) 的代码:
xml 看起来像这样:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:id="@+id/ts_fragment">
.
.-->other stuff
.
这里是添加片段的代码:
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(fragmentLayout,container,false);
setGraphics(view); //custom function which gets views and sets gui.
return view;
}
视图获得了“fragmentLayout”的 ID,但片段获得了不同的 ID,即容器 ID,这使得我的片段将自己置于另一个没有区分 ID 的位置。
如何避免这种情况?谢谢。
编辑
我尝试使用类似:topFragment.getId(),但它返回 containerID。 javadoc 说:
返回这个片段所知道的标识符。这要么是 android:id 布局中提供的值或容器视图 ID 添加片段时提供。
我只是不想要容器视图 ID,有没有办法强制片段具有 android:id 值?
更新
尝试打印不同的 id:
My_Android: Main layout has id: 2131492958 //R.id.MainLayout ->ContainerID
My_Android: MyTopFragment{5cd93c9} - id: 2130968617 //R.id.ts_fragment value
My_Android: MyBottomFragment{2055ace} - id: 2130968601 //R.id.bs_fragment value
My_Android: MyTopFragment has ID: 2131492958 //After inflating process, the fragment gets this id, the same of R.id.MainLayout
My_Android: MyBottomFragment has ID: 2131492958 //Idem
【问题讨论】:
-
是的。使用 fragment.setTag()
-
@TinTran 会强制片段获取 android:id 值吗?
-
Fragment 默认有容器的 id。 Android:id 是片段中视图的 id。标签和片段 id 不相关
标签: android android-layout android-fragments