我如何改变按钮边际与LiveData和BindingAdapter?我的LiveData在ViewModel:var marginRight = MutableLiveData(R.dimen.default_margin)
我dimen<dimen name="default_margin">141dp</dimen>
和我的属性:android:layout_marginEnd="@{viewmodel.marginRight}"
在这个例子中我得到
Cannot find a setter for <android.widget.Button android:layout_marginEnd> that accepts parameter type 'androidx.lifecycle.MutableLiveData<java.lang.Integer>'
If a binding adapter provides the setter, check that the adapter is annotated correctly and that the parameter type matches.
你有维度id而不是维度值在你的mutableelvedata,但我认为你不能在xml中这样做,因为视图没有设置边距。你可以在代码中使用MarginLayoutParams。
在网上搜索后,我发现没有设置边距。它帮助了我:
LiveData:
var marginRight = MutableLiveData(R.dimen.margin_right_default)
我BindingAdapter:
@JvmStatic
@BindingAdapter("app:marginRight")
fun setMarginRight(view: View, marginResource: Int){
val resources = view.context.resources
val params = view.layoutParams as ViewGroup.MarginLayoutParams
params.setMargins(0,0, resources.getDimension(marginResource).toInt(), 0)
view.layoutParams = params
}
和我的属性:
app:marginRight="@{viewmodel.marginRight}"