對於數據綁定layout_width或其他佈局屬性來說,這似乎並不是很直接。 如果我嘗試像android:layout_width="@{viewModel.heading3.width}
那樣直接綁定它 - >它不能編譯。如何將layout_width值與使用數據綁定的ViewModel綁定
添加綁定適配器像下面後拋出運行時異常提供layout_width
@BindingAdapter("android:layout_width")
public static void setLayoutWidth(View view, int width) {
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = width;
view.setLayoutParams(layoutParams);
}
我怎樣才能做到TextView的身高和體重使用數據綁定的模式來控制。我可以在代碼背後嘗試它,但對我來說,數據綁定方法似乎更適合我的場景。
謝謝。
編輯: 作爲建議我走過了,但我的問題是不同的:Android Data Binding layout_width and layout_height
我不打算來讀取XML捫寬度值,我想從視圖模型讀取它。這是我的視圖模型的外觀
public class HeadingViewModel {
public HeadingViewModel(String heading, int width) {
this.heading = heading;
this.width = width;
}
String heading;
int width;
public String getHeading() {
return heading;
}
public int getWidth() {
return width;
}
然後我現在試圖用這樣的默認值:
<TextView
android:layout_width="@{viewModel.heading1.width, default=match_parent}"
android:layout_height="50dp" android:text="@{viewModel.heading1.heading}" android:id="@+id/heading"
android:background="@android:color/holo_blue_light"/>
不過這個數據綁定不工作。讓我知道如果我仍然在建議的線程中缺少某些東西。
請參閱[Android數據綁定佈局\ _width和佈局\ _height](https://stackoverflow.com/questions/35295120/android-data-binding-layout-width-and-layout-height) –
@RaviRupareliya讓我知道如果你仍然認爲這是重複的 – PKV