目前我正在为 android 开发一个应用程序并为我的图形用户界面使用数据绑定(bind)。
我的问题是我要显示的数据没有自动刷新。
我认为我的问题的根源是我将多个 subview 膨胀到我的 Root View 中。我的 View 层次结构看起来像这样:
- layout_activity_main
- fragment_layout_0(此处没有数据绑定(bind))
- fragment_layout_1(显示特定设备详细信息的布局)
- process_data_view
- value_0_view
- value_1_view
- ...
- 界面 View
- ...
- process_data_view
我对 process_data_view 和 value_x_view 使用数据绑定(bind),以便自动刷新 View 。如果设备不包含过程数据,则 process_data_view 应该是不可见的。直到此时它工作正常,因为设备的数据绑定(bind)是在 fragment 的 onCreateView 方法中设置的。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater,R.layout.layout_details_new,container,false);
return binding.getRoot();
}
当没有过程数据时, View 是不可见的,而当我在运行时接收到过程数据时, View 会自动变为可见。
但现在我想为 value_x_view 膨胀另一个 xml 文件。我像这样给它充气:
private void setValue(View view, int value){
ValueViewBinding valueBinding = DataBindingUtil.inflate(getLayoutInflater(null), R.layout.value_view, (LinearLayout)view, false);
valueBinding.setValue(value)
View valueView = valueBinding.getRoot();
((LinearLayout) view).addView(valueView);
}
*参数“view”是父 fragment 布局中的LinearLayout
当我运行应用程序并且它们正确显示时,我膨胀了大约 12 个 value_views。唯一的问题是他们没有得到刷新。它们仅显示在 value_view 膨胀时有效的值。
有没有办法让数据绑定(bind)工作。我错过了什么或我做错了什么?
最佳答案
这段代码:
private void setValue(View view, int value){
ValueViewBinding valueBinding = DataBindingUtil.inflate(getLayoutInflater(null), R.layout.value_view, (LinearLayout)view, false);
valueBinding.setValue(value)
View valueView = valueBinding.getRoot();
((LinearLayout) view).addView(valueView);
}
有点问题。通货膨胀和值(value)设定正在以相同的方法完成。这意味着如果您想调整该值,您最终会膨胀并添加一个新 View ,我认为您不想这样做。
也许您更愿意在布局中使用 ViewStub。然后,当您想要对其充气时,只需将其设置为可见即可。然后变量赋值都毫不费力地保持最新。
<layout ...>
<data><variable name="value" type="int"/></data>
<LinearLayout ...>
<!-- other layouts -->
<ViewStub android:id="@+id/lateInflation" app:value="@{value}"/>
</LinearLayout>
</layout>
您的另一个选择是向绑定(bind)添加一个监听器,每当值发生变化时,您自己更新膨胀的布局。这是更多的工作:
private void setValue(View view, int value){
final ValueViewBinding valueBinding = DataBindingUtil.inflate(getLayoutInflater(null), R.layout.value_view, (LinearLayout)view, false);
valueBinding.setValue(value)
View valueView = valueBinding.getRoot();
((LinearLayout) view).addView(valueView);
// I don't know what your containing
final LayoutDetailsNewBinding binding = DataBindingUtil.findBinding(view);
binding.addOnPropertyChangedCallback(new OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(Observable sender, int propertyId) {
// assume the variable name in LayoutDetailsNewBinding is 'value'
if (propertyId == BR.value) {
valueBinding.setValue(binding.getValue());
}
}
}
}
关于android - android中膨胀布局的数据绑定(bind)不会刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38950965/