Andy the android Andy the android - 4 months ago 35
Android Question

LinearLayout gravity inside RecyclerView

Hey I'm making a simple chat application. I'm having these two layouts to pass for the inflater to add to the RecyclerView:

received_msg.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#f00">

<TextView
android:text="Hello"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>


sent_msg.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#fff"
android:layout_gravity="right">

<TextView
android:text="Text"
android:textColor="#f00"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>


RecyclerView:

<android.support.v7.widget.RecyclerView
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbarStyle="outsideOverlay"
android:scrollbars="vertical" />


The layout_gravity property seem to have no effect on the sent_msg.xml's LinearLayout. What to do?

Answer

You can make the two item XML's full width (match_parent) and move the layout_gravity and background attributes to the child TextView:

sent_msg.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"                  (* Changed)
    android:layout_height="wrap_content">

<TextView
    android:text="Text"
    android:background="#fff"                            (* Changed)
    android:textColor="#f00"
    android:layout_gravity="right"                       (* Changed)
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>