2017-07-11 128 views
-2

對於數據綁定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"/> 

不過這個數據綁定不工作。讓我知道如果我仍然在建議的線程中缺少某些東西。

+1

請參閱[Android數據綁定佈局\ _width和佈局\ _height](https://stackoverflow.com/questions/35295120/android-data-binding-layout-width-and-layout-height) –

+0

@RaviRupareliya讓我知道如果你仍然認爲這是重複的 – PKV

回答

1

float值試試吧,它會工作的width也是它

@BindingAdapter("android:layout_width") 
public static void setLayoutWidth(View view, float width) { 
    ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); 
    layoutParams.width = (int)width; 
    view.setLayoutParams(layoutParams); 
} 

和變化的數據類型在你HeadingViewModel

+1

它的工作。謝謝。你能建議爲什麼我們必須從int轉換爲浮動然後返回? – PKV

+0

我也想知道同樣的事情,首先我只用'int'嘗試,但出現錯誤,說'你必須指定屬性layout_width'。所以我想給它一個嘗試與'浮動',它的工作 –

+0

不知道這個問題仍然值得-2 :) – PKV