我目前开始使用数据绑定库,在我的viewmodel中我有一个扩展的LiveData对象:
public class ScannerViewModel extends AndroidViewModel {
/** MutableLiveData containing the scanner state to notify MainActivity. */
public ScannerLiveData scannerLiveData;
ScannerLiveData:
public class ScannerLiveData extends MutableLiveData<ScannerLiveData> {
public boolean mScanningStarted;
public boolean mBluetoothEnabled;
public boolean mLocationEnabled;
public ScannerLiveData(final boolean bluetoothEnabled, final boolean locationEnabled) {
mScanningStarted = false;
mBluetoothEnabled = bluetoothEnabled;
mLocationEnabled = locationEnabled;
postValue(this);
}
...
}
activity_scanner.xml:
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_test">
<data>
<import type="android.view.View" />
<variable
name="livedata"
type="de.datacollect.ecount.ui.scanner.ScannerLiveData" />
</data>
...
<android.support.constraint.ConstraintLayout
<ProgressBar
android:id="@+id/state_scanning"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="-7dp"
android:layout_marginTop="-8dp"
android:indeterminate="true"
android:indeterminateTint="@android:color/white"
android:visibility="@{livedata.mBluetoothEnabled ? View.VISIBLE : View.INVISIBLE}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/recycler_view_ble_devices" />
...
ScannerActivity:
@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityScannerBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_scanner);
// Create view model containing utility methods for scanning
mScannerViewModel = ViewModelProviders.of(this).get(ScannerViewModel.class);
mScannerViewModel.getScannerState().observe(this, this::startScan);
binding.setLifecycleOwner(this);
binding.setLivedata(mScannerViewModel.scannerLiveData);
...
如何绑定mBluetoothEnabled
属性?我在构建时遇到了一个未分类的错误。我已经使用了搜索,但没有找到它的相关信息。每一个帮助都会受到赞赏。
顺便说一下:
数据绑定的更新:
现在,您可以将LiveData对象用作数据绑定表达式中的可观察字段。 ViewDataBinding类现在包含一个新的setLifecycle方法,您需要将其用于观察LiveData对象。
答案 0 :(得分:0)
不是绑定LiveData对象,而是绑定您的视图模型。因此,将activity_scanner.xml中的 livedata 变量更改为
<variable
name="viewModel"
type="de.datacollect.ecount.ui.scanner.ScannerViewModel" />
和在ScannerActivity中
binding.setViewModel(mScannerViewModel);
然后您的绑定表达式将变为
android:visibility="@{viewModel.scannerLiveData.mBluetoothEnabled ? View.VISIBLE : View.INVISIBLE}"