java Android 数据绑定 layout_width 和 layout_height

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35295120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:58:10  来源:igfitidea点击:

Android Data Binding layout_width and layout_height

javaandroidmvvmdata-binding

提问by John Murphy

I need to be able to dynamically set an EditText's height property. I am using data binding for other properties throughout my app, so I would love to be able to use data binding to control the height of my elements. Here is a stripped down version of my xml:

我需要能够动态设置 EditText 的高度属性。我在整个应用程序中为其他属性使用数据绑定,因此我希望能够使用数据绑定来控制元素的高度。这是我的 xml 的精简版本:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable name="loginVM" type="com.testing.stuff.ViewModels.LoginViewModel" />
</data>

<EditText android:inputType="number"
            android:id="@+id/txtVerificationCode"
            android:layout_height="@{loginVM.compact ? @dimen/verificationHeightCompact : @dimen/verificationHeightFull}"
            android:layout_width="match_parent"
            android:paddingRight="16dp"
            android:paddingLeft="16dp"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:layout_marginLeft="10dp"
            android:alpha="@{loginVM.verificationOpacity}"
            android:layout_marginStart="10dp"
            android:textAlignment="center"
            android:visibility="visible"
            android:hint="Enter verificationCode"
            android:text="@{loginVM.verificationCode}" />
</layout> 

And here is a stripped down version of my View Model:

这是我的视图模型的精简版:

public class LoginViewModel extends BaseObservable {
public final ObservableField<String> verificationCode; 
public final ObservableField<Boolean> compact;

@Bindable
public String getVerificationCode() {
    if (this.verificationCode == null) {
        return "";
    } else {
        return this.verificationCode.get();
    }
}

public void setVerificationCode(String verificationCode) {
    this.verificationCode.set(verificationCode);
    invalidateProperties();
}

@Bindable
public Boolean getCompact(){return this.compact.get();}

public void setCompact(Boolean value)
{
    this.compact.set(value);
    this.invalidateProperties();
}

@BindingAdapter("android:layout_height")
public static void setLayoutHeight(EditText view, float height)
{
    ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
    layoutParams.height = (int)height;
    view.setLayoutParams(layoutParams);
}

public LoginViewModel(Context ctx) {
    verificationCode = new ObservableField();
    compact = new ObservableField();
}

The dimensions are in the dimens.xml file. And I am modifying the properties in the view model. But, when I launch the app, I'm getting the following error immediately after launch (the bindingadapter is not firing on debug). I have several other elements on the screen but this particular one is the one I need to change the height when a particular action occurs:

尺寸位于 dimens.xml 文件中。我正在修改视图模型中的属性。但是,当我启动应用程序时,我在启动后立即收到以下错误(绑定适配器未在调试时触发)。我在屏幕上还有其他几个元素,但这个特定的元素是我在发生特定操作时需要更改高度的元素:

FATAL EXCEPTION: main

Process: com.testing.stuff, PID: 32752

java.lang.RuntimeException: Unable to start activity  
ComponentInfo{com.testing.stuff/com.testing.stuff.Login}: 
java.lang.RuntimeException: Binary XML file line #69: You must supply 
a layout_height attribute.

Caused by: java.lang.RuntimeException: Binary XML file line #69: You 
must supply a layout_height attribute.

There are a few posts on SO regarding this issue but no definitive answers or the approach did not work. Surely this is an implementation that is common. Thanks in advance for the help.

关于这个问题,有一些关于 SO 的帖子,但没有明确的答案或方法不起作用。当然,这是一个常见的实现。在此先感谢您的帮助。

回答by Phan Van Linh

In Java

在 Java 中

@BindingAdapter("layout_height")
public static void setLayoutHeight(View view, float height) {
    LayoutParams layoutParams = view.getLayoutParams();
    layoutParams.height = height;
    view.setLayoutParams(layoutParams);
}

And in your XML

在你的 XML 中

app:layout_height="@{ viewModel.isBig ? @dimen/dp_20 : @dimen/dp_5 }"

import the app like this

像这样导入应用程序

xmlns:app="http://schemas.android.com/apk/res-auto"

回答by yigit

When data binding is used, we strip values from the XML. You can add a default value to be used when it is stripped to avoid the issue.

当使用数据绑定时,我们从 XML 中剥离值。您可以添加要在剥离时使用的默认值以避免该问题。

see: http://developer.android.com/tools/data-binding/guide.html(bottom of the page).

请参阅:http: //developer.android.com/tools/data-binding/guide.html(页面底部)。

android:layout_height="@{loginVM.compact ? @dimen/verificationHeightCompact : @dimen/verificationHeightFull, default=wrap_content}"

回答by KubaK

According to the discussion on Android issue tracker, it is impossible to set layout height or width with data binding without creating custom binding adapters:

根据 Android 问题跟踪器上的讨论,在不创建自定义绑定适配器的情况下,无法使用数据绑定设置布局高度或宽度:

https://code.google.com/p/android/issues/detail?id=180666

https://code.google.com/p/android/issues/detail?id=180666

The binding adapter needed for setting view height would look like that:

设置视图高度所需的绑定适配器如下所示:

@BindingAdapter("android:layout_height")
public static void setLayoutHeight(View view, int height) {
    LayoutParams layoutParams = view.getLayoutParams();
    layoutParams.height = height;
    view.setLayoutParams(layoutParams);
}

回答by Andreas Rudolph

I solved it like this in Kotlininstead of Java.

我在Kotlin而不是Java 中解决了这个问题。

Make a file called

制作一个名为

MyBindings.kt

And put in:

并输入:

@BindingAdapter("bind:customHeight")
fun setLayoutHeight(view: View, height: Float) {
    view.layoutParams = view.layoutParams.apply { this.height = height.toInt() }
}

And then you can use this in your layouts:

然后你可以在你的布局中使用它:

<EditText 
android:id="@+id/internalTopDisplay"
android:layout_width="match_parent"
bind:customHeight="@{loginVM.compact ? @dimen/verificationHeightCompact : @dimen/verificationHeightFull}"
android:layout_height="wrap_content"/>

回答by Malek Hijazi

You can add a binding adapter for android:layout_heightthat takes in a float.

您可以为android:layout_height添加一个接受浮点数的绑定适配器。

For height:

对于高度

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

For width:

对于宽度:

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

Usage:

用法

android:layout_width="@{model.isBig ? @dimen/big_dimen : @dimen/small_dimen, default=wrap_content}"

android:layout_height="@{model.isBig ? @dimen/big_dimen : @dimen/small_dimen, default=wrap_content}"

PS: Don't forget to set a default value

PS:不要忘记设置默认值

回答by Camino2007

For me did this the trick:

对我来说,这就是诀窍:

    @BindingAdapter("android:layout_height")
    public static void setLayoutHeight(View view, final Number height) {
        final ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.height =  height.intValue();
        view.setLayoutParams(layoutParams);
    }

And the xml:

和 xml:

android:layout_height="@{item.isItemCollapsed ? @dimen/radar_item_first_background_height  : item.textMaxLines, default=@dimen/radar_item_first_background_height}"