Android: How to remove margin/padding in Preference Screen

Updating this for androidx.

After a lot of experimentation, I resolved this issue by adding this to each preference that had the excess indentation:

app:iconSpaceReserved="false"

Of course, you’ll also need to add this to the PreferenceScreen declaration itself at the top of your xml:

xmlns:app="http://schemas.android.com/apk/res-auto"

Follow Up For Custom Preferences

I noticed that in the case of custom preferences, particularly on older devices, this solution wasn’t always working. For example, a preference like this could still be indented:

com.example.preference.SomeCustomPreference
    android:id="@+id/some_custom_preference"
    android:name="Custom Preference"
    android:key="@string/custom_pref_key"
    android:summary="@string/custom_pref_summary"
    android:title="@string/preference_custom_title"
    app:iconSpaceReserved="false"

The problem traces to the usage of the third constructor parameter in the custom preference class. If you pass that third parameter, the list item will be indented. If you omit it, the list will be aligned correctly:

class SomeCustomPreference
@JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = android.R.attr.someCustomPreferenceStyle
) : DialogPreference(context, attrs, defStyle) {

    override fun getDialogLayoutResource(): Int {
        return R.layout.my_layout
    }
}

Instead of that, use this:

class SomeCustomPreference
@JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : DialogPreference(context, attrs) {

    override fun getDialogLayoutResource(): Int {
        return R.layout.my_layout
    }
}

Credit for this goes to @CommonsWare in this very old post.

Leave a Comment