Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set match_parent and wrap_content depending on condition in xml?

Tags:

android

height

I need to set the layout_height of TextView depending on some condition. I have tried with importing LayoutParams but it did not work. Any ideas?

android:layout_height="condition ? wrap_content : match_parent"

I need to do it in xml not with code

like image 631
Kristiyan Gergov Avatar asked Sep 17 '18 05:09

Kristiyan Gergov


2 Answers

You can do it with a custom Binding Adapter.

Create Binding Adapter as below

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);
    }
}

Then use this attribute in your View.

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

Note:

default = wrap_content is important, because width and height should be specified when view is created, whether binding happens after bit time of view rendering.

Explaination

Why it is not possible without BindingAdapter.

Because Android does not provide View.setWidth(), size can be set by class LayoutParams, so you have to use LayoutParams. You can not use LayoutParams in xml because again here is no View.setWidth() method.

That's why below syntax gives error

Cannot find the setter for attribute 'android:layout_width' with parameter type int

<data>

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

<data>

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

Setting Visibility by xml works, because there is View.setVisibility() method available

Below syntax works

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

<FrameLayout android:visibility="@{sale ? View.GONE : View.VISIBLE}"/>
like image 186
Khemraj Sharma Avatar answered Oct 19 '22 23:10

Khemraj Sharma


You should change it via 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);}
like image 2
Kevin Kurien Avatar answered Oct 20 '22 00:10

Kevin Kurien