android自动升级库,android – 使用数据绑定库更新UI
语境:我有以下视图模型:public class DrawerPageHeaderViewModelImpl extends BaseObservable implements DrawerPageHeaderViewModel {@Nullableprivate Location currentLocation;public DrawerPageHeaderViewModelImpl(@Null
语境:
我有以下视图模型:
public class DrawerPageHeaderViewModelImpl extends BaseObservable implements DrawerPageHeaderViewModel {
@Nullable
private Location currentLocation;
public DrawerPageHeaderViewModelImpl(@Nullable final Location currentLocation) {
this.currentLocation = currentLocation;
}
@Bindable
@Nullable
@Override
public String getDistanceDisplayString() {
if (currentLocation == null) {
return null;
}
float[] results = new float[1];
Location.distanceBetween(landmark.getLatitude(), landmark.getLongitude(), currentLocation.getLatitude(), currentLocation.getLongitude(), results);
final float metersToTargetLocation = results[0];
final float feetToTargetLocation = DistanceUtil.convertMetersToFeet(metersToTargetLocation);
return DistanceUtil.convertFeetToFeetOrMilesString(feetToTargetLocation);
}
@Override
public void setCurrentLocation(@Nullable final Location currentLocation) {
this.currentLocation = currentLocation;
notifyPropertyChanged(BR.distanceDisplayString);
}
}
此视图模型将传递给Fragment并存储在实例变量中.然后视图模型绑定到Fragment的onCreateView回调中的布局(此处headerView是一个空的FrameLayout):
@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_drawer_page, container, false);
headerView = (ViewGroup) v.findViewById(R.id.headerView);
final ViewDrawerPageHeaderBinding binding = DataBindingUtil.inflate(inflater, R.layout.view_drawer_page_header, headerView, true);
binding.setViewModel(viewModel);
return v;
}
定期调用viewModel.setCurrentLocation并传递用户的当前位置:
@Override
public void update(final Observable observable, Object data) {
new Handler(Looper.getMainLooper()).post(() -> {
if (isAdded()) {
viewModel.setCurrentLocation(locationController.getCachedUserLocation());
}
});
}
目前的行为:
在首次创建每个片段时,UI会正确显示距离String.每次重新创建片段时,UI都会正确显示距离String(这些片段位于ViewPager中.
使用新位置调用viewModel.setCurrentLocation时,UI不会更新.
期望的行为:
每次使用新位置调用viewModel.setCurrentLocation时,UI都会更新.
到目前为止我看过/想过的东西:
据我所知,让视图模型实现Observable(在这种情况下,通过扩展BaseObservable)应该在调用notifyPropertyChanged时自动进行UI更新.至少,当我看到the Android documentation for data binding时,这就是我带走的信息.
BaseObservable类维护一个OnPropertyChangedCallbacks的私有列表.如果我在BaseObservable.notifyPropertyChanged方法上设置调试断点:
public void notifyPropertyChanged(int fieldId) {
if(this.mCallbacks != null) {
this.mCallbacks.notifyCallbacks(this, fieldId, (Object)null);
}
}
我看到mCallbacks在运行时始终为null.因此,假设生成的数据绑定内容不会调用BaseObservable.addOnPropertyChangedCallback来提供自动连接组件的OnPropertyChangedCallback.这是否意味着我需要手动完成?这似乎打败了数据绑定库的许多重点.
更多推荐
所有评论(0)