Android 数据绑定:如何绑定要包含的布局标识符
Android databinding : how can I bind a layout identifier to include
我想包含一个带有数据绑定的布局。
我想使用 enum
将 id 从 java 传递到我的布局,但我似乎找不到正确的语法。
这是我的 class 片段 enum
和 onCreateView()
:
private enum TYPE{
A(R.layout.fragment_item_A),
B(R.layout.fragment_item_B),
C(R.layout.fragment_item_C);
public final int id;
TYPE(int id) {
this.id = id;
}
private int getId(){
return id;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//...
this.type = TYPE.A;
FragmentItemBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_item, container, false);
tmpView = binding.getRoot();
binding.setType(type);
//...
return tmpView;
}
我想膨胀 R.layout.fragment_item
并使其包含 R.layout.fragment_item_A
(或其他类型)。
这是我在 R.layout.fragment_item XML 文件中的失败尝试:
<data>
<variable name="type" type="com.dan.myapp.fragments.MyFragmentClass.TYPE"/>
...
</data>
<include layout="@{type.id}" <!-- layout="@layout/fragment_item_A"-->
android:id="@+id/included_item"/>
include中的绑定应该怎么写?
PS : 也许答案在 or in 中,但我没找到...
我很确定你不能那样做。数据绑定需要编译类型的布局,以便它可以确定传递变量等的类型。
相反,我认为您可以这样做:
<FrameLayout ...>
<ViewStub android:layout="@layout/fragment_item_a"
android:visibility="@{type == Type.A ? View.VISIBLE : View.GONE}" .../>
<ViewStub android:layout="@layout/fragment_item_b"
android:visibility="@{type == Type.B ? View.VISIBLE : View.GONE}" .../>
<ViewStub android:layout="@layout/fragment_item_c"
android:visibility="@{type == Type.C ? View.VISIBLE : View.GONE}" .../>
</FrameLayout>
我想包含一个带有数据绑定的布局。
我想使用 enum
将 id 从 java 传递到我的布局,但我似乎找不到正确的语法。
这是我的 class 片段 enum
和 onCreateView()
:
private enum TYPE{
A(R.layout.fragment_item_A),
B(R.layout.fragment_item_B),
C(R.layout.fragment_item_C);
public final int id;
TYPE(int id) {
this.id = id;
}
private int getId(){
return id;
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//...
this.type = TYPE.A;
FragmentItemBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_item, container, false);
tmpView = binding.getRoot();
binding.setType(type);
//...
return tmpView;
}
我想膨胀 R.layout.fragment_item
并使其包含 R.layout.fragment_item_A
(或其他类型)。
这是我在 R.layout.fragment_item XML 文件中的失败尝试:
<data>
<variable name="type" type="com.dan.myapp.fragments.MyFragmentClass.TYPE"/>
...
</data>
<include layout="@{type.id}" <!-- layout="@layout/fragment_item_A"-->
android:id="@+id/included_item"/>
include中的绑定应该怎么写?
PS : 也许答案在
我很确定你不能那样做。数据绑定需要编译类型的布局,以便它可以确定传递变量等的类型。
相反,我认为您可以这样做:
<FrameLayout ...>
<ViewStub android:layout="@layout/fragment_item_a"
android:visibility="@{type == Type.A ? View.VISIBLE : View.GONE}" .../>
<ViewStub android:layout="@layout/fragment_item_b"
android:visibility="@{type == Type.B ? View.VISIBLE : View.GONE}" .../>
<ViewStub android:layout="@layout/fragment_item_c"
android:visibility="@{type == Type.C ? View.VISIBLE : View.GONE}" .../>
</FrameLayout>