Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage dividers in a PreferenceFragment?

I started dealing with preferences in a PreferenceFragment. Here's what I have:

my_preferences

I'm trying to:

  1. get rid of the dividers between items. I suppose this can be defined from styles, but I can't figure out how. I tried getting the preference ListView at runtime calling findViewById(android.R.id.list), as I read somewhere, but it returns null.

  2. set new, full width dividers right on top of the headers, as seen here. For example in this case I want a full width divider right above "Statistiche", but not above "Generali" which is on top of the list.

The only way that comes to my mind is setting dividers as fake preferences, like with:

<Preference
    android:layout="@layout/divider" //here I set width and a divider resource
    />

<PreferenceCategory ... />

The main issue here is that my PreferenceFragment (or the ActionBarActivity it's in) has some left/right padding, that make any divider I add into preferences.xml not cover the entire width.

So my question are:

  • How can I get rid of default, item-item dividers that you can see in the image?

  • How can I set full width dividers right above headers, or how can I get rid of internal fragment/activity padding? Of course my activity layout has no (explicit) padding whatsoever.

like image 415
natario Avatar asked Sep 06 '25 03:09

natario


2 Answers

AndroidX makes it simple, but I wish it was better documented.

In XML

To add/remove dividers between preferences in XML, use the following attributes:

<androidx.preference.PreferenceScreen
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <Preference
        ...
        app:allowDividerAbove="true/false"
        app:allowDividerBelow="true/false"
        ... />

</androidx.preference.PreferenceScreen>

Note, a divider will only be shown between two preferences if the top divider has allowDividerBelow set to true and the bottom divider has allowDividerAbove set to true.

In Code

You can also change/remove dividers programmatically using the following methods in onActivityCreated of your PreferenceFragmentCompat:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // To remove:
    setDivider(null);

    // To change:
    setDivider(ContextCompat.getDrawable(getActivity(), R.drawable.your_drawable));
    setDividerHeight(your_height);
}
like image 128
Maksim Ivanov Avatar answered Sep 07 '25 22:09

Maksim Ivanov


Add this code under the PreferenceFragment :

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // remove dividers
        View rootView = getView();
        ListView list = (ListView) rootView.findViewById(android.R.id.list);
        list.setDivider(null);

    }
like image 40
SagiLow Avatar answered Sep 07 '25 21:09

SagiLow