is a microblog
home archives search feed blogroll

Dividers With Insets On Android

Table dividers with insets just look much better. Apple knows this. The default table separators on iOS have inset values. Android has not caught up yet. If you want insets, you have to get your hands dirty. Programmatically dirty.

Here’s what a list looks like on Android.

List Without Divider Insets

Here’s the same list with divider insets. It looks better.

List With Divider Insets

I found this code on Stack Overflow.

<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<shape android:shape="rectangle" >
<solid android:color="#fff" />

<shape android:shape="rectangle" >
<solid android:color="#ccc"/>

The solution has the downside that the colors or the insets cannot be edited programmatically. If your app does not support theming, this is a fine way to do it. However, one of my Android app supports theming, I needed the colors to be editable programmatically. I created the function below.

public LayerDrawable createDivider(int backgroundColor, int foregroundColor) {
    ColorDrawable backgroundDrawable = new ColorDrawable();

    InsetDrawable foregroundDrawable = new InsetDrawable(
            new ColorDrawable(foregroundColor),
            50 /* left */,
            0 /* top */,
            50 /* right */,
            0 /* bottom */);

    Drawable[] layers = {backgroundDrawable, foregroundDrawable};
    LayerDrawable layerDrawable = new LayerDrawable(layers);

    return layerDrawable;

It’s essentially the same as the XML drawable code, but it’s implemented in Java. You can pass the colors you want as parameters. You could also add parameters for the inset values if you wish.

You can use this function like this.

ListView myListView = (ListView) findViewById(R.id.my_listview);
myListView.setDivider(createDivider(Color.BLACK, Color.WHITE));
myListView.setDividerHeight(2); // Default is 0.

Don’t forget to set the divider’s height. The default value is 0. Your dividers won’t show up otherwise.

Posted on 2018-03-15   #android     #java  

← Next post    ·    Previous post →