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
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.
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}"
View.setVisibility() method availableBelow syntax works
<data>
<import type="android.view.View"/>
<variable
name="sale"
type="java.lang.Boolean"/>
</data>
<FrameLayout android:visibility="@{sale ? View.GONE : View.VISIBLE}"/>
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);}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With