如何根据xml中的条件设置match_parent和wrap_content?

时间:2018-09-17 05:58:13

标签: android height

我需要根据某些条件设置TextView的layout_height。我曾尝试导入LayoutParams,但没有成功。有什么想法吗?

android:layout_height="condition ? wrap_content : match_parent"

我需要使用xml而不是代码

5 个答案:

答案 0 :(得分:1)

您可以使用自定义的Binding Adapter

  

按如下所示创建绑定适配器

public class DataBindingAdapter {
    @BindingAdapter("android:layout_width")
    public static void setWidth(View view, boolean isMatchParent) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.width = isMatchParent ? MATCH_PARENT : WRAP_CONTENT;
        view.setLayoutParams(params);
    }
}

然后在您的View中使用此属性。

<TextView
    android:layout_width="@{item.isMatchParent, default = wrap_content}"
    ...
/>

注意:

default = wrap_content很重要,因为创建视图时应指定宽度和高度,绑定是否在视图渲染的一段时间后发生。

说明

为什么没有BindingAdapter是不可能的。

由于Android不提供View.setWidth(),因此可以通过类LayoutParams设置大小,因此您必须使用LayoutParams。您不能在xml中使用LayoutParams,因为这里再次没有View.setWidth()方法。

这就是下面的语法给出错误的原因

  

找不到参数类型为int的属性“ android:layout_width”的设置器

<data>

    <import type="android.view.ViewGroup.LayoutParams"/>

<data>

android:layout_width="@{item.matchParent ? LayoutParams.MATCH_PARENT : LayoutParams.WRAP_CONTENT}"

通过xml设置可见性是可行的,因为有View.setVisibility()方法可用

以下语法有效

<data>
    <import type="android.view.View"/>
    <variable
        name="sale"
        type="java.lang.Boolean"/>
</data>

<FrameLayout android:visibility="@{sale ? View.GONE : View.VISIBLE}"/>

答案 1 :(得分:0)

  

我认为您使用提供所有解决方案的ConstraintLayouts

答案 2 :(得分:0)

if(a == b ) {

view.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));

} 
else 
{
view.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}

答案 3 :(得分:0)

您应该通过LayoutParams进行更改:

    if(condition){
    LayoutParams params = (LayoutParams) textView.getLayoutParams();
    params.height = MATCH_PARENT;
    textView.setLayoutParams(params);}
else{
LayoutParams params = (LayoutParams) textView.getLayoutParams();
    params.height = WRAP_CONTENT;
    textView.setLayoutParams(params);}

答案 4 :(得分:0)

<layout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:app="http://schemas.android.com/apk/res-auto"  
    xmlns:tools="http://schemas.android.com/tools">  

    <data>  

        <variable  
            name="user"  
            type="<package name>.UserModel" />  

        <import type="android.view.View"/>  
    </data>  

    <RelativeLayout  
        android:layout_width="match_parent"  
        android:layout_height="match_parent">  

        <TextView  
             android:layout_width="@{user.email.trim().length()>10 ? wrap_content : match_parent}""  
             android:layout_height="wrap_content"  
             android:text="@{user.email}"  />  

    </RelativeLayout>  
</layout>    

在这里尝试从here获得此解决方案