anony anony - 9 days ago 5
Android Question

Android recyclerview divider aligned to internal layout views

I know this gotta have a simple answer, so here goes:

This is an image of a famous "chat" Android app. My question is how can I simulate the behaviour in red, namely a divider that does not take the parent's screen width, but starts aligned with the text views in the recyclerview item inflated layout?

enter image description here

I have created a

chatlist_divider.xml
drawable as below:

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="80dp"
android:insetRight="16dp">
<shape>
<size android:height="1dp"/>
<padding
android:bottom="2dp"
android:left="8dp"
android:right="8dp"
android:top="2dp"/>
<solid android:color="@color/colorDivider"/>
<corners android:radius="48dp" />
</shape>
</inset>


and programatically have used it as follows:

mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), R.drawable.chatlist_divider));


but ofc the result will not be as perfect as in the image above, because Im playing with the
insetLeft
property of the inset, until it feels right:

enter image description here

Is this the best that can be done? I wanted a proper and definite alignment to the TextViews inside the inflated layout of each list item, not just trial and error.

(I could also create a
<View>
below the textviews (which are in a Layout of its own) to simulate the divider, but then how can I assign it the .xml drawable?)

Any thoughts?

Answer

No need to use mRecyclerView.addItemDecoration.

Simply create the divider as a regular View with your drawable xml as background and add it to your item's layout xml.

If you make the root of the layout RelativeLayout, you can have the divider toRightOf="@+id/some_other_view", so it's aligned properly with the item's views.

<View
    android:id="@+id/divider"
    android:layout_width="match_parent"
    android:layout_height="3dp"
    android:layout_toRightOf="@+id/my_photo_view"
    android:background="@drawable/chatlist_divider" />
Comments