'View margin not working after using databinding
Below is the code of the item layout of gridview. In this, the layout_margin is there in the design panel but when I run the there is no margin. I tried to check other tags like the background and found that it was working. A similar problem is with the layout_weights of linear_layout, the are also not working. These were working fine without data binding. Can someone please help me out in resolving this? '''
<?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"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="localEntry"
type="com.example.lo_cal.data.models.LoCalEntry" />
</data>
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/small"
android:background="@color/colorAccent"
android:orientation="vertical">
<TextView
android:id="@+id/item_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:itemId="@{localEntry}"
tools:text="ID" />
<TextView
android:id="@+id/item_first_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{localEntry.firstName}"
tools:text="shashank" />
<TextView
android:id="@+id/item_second_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{localEntry.secondName}"
tools:text="mohabia" />
<TextView
android:id="@+id/item_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{localEntry.result}"
tools:text="100" />
</androidx.appcompat.widget.LinearLayoutCompat>
</layout>
'''
Solution 1:[1]
I faced this problem when inflate the view. Previously,
mBinding = FragmentxxBinding.inflate(inflater);
After I change to
mBinding = FragmentxxBinding.inflate(inflater, container, false);
the problems solved, hope this can help.
Solution 2:[2]
I faced the same issue, and found out that, when using dataBinding, the margin is ignored for the direct children of the dataBinding , and will always stretch to fill any space around.
The simples way to solve it is to wrap the view from which you want a margin in a frameLayout for exemple, so that even the frameLayout is stretched, the view inside it will keep it position and its margins.
so in your case, what you need is to just wrap your
<androidx.appcompat.widget.LinearLayoutCompat> in another layout on which you can set the width and height to wrap_content.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user2301281 |
| Solution 2 | Dharman |
