I started dealing with preferences in a PreferenceFragment
. Here's what I have:
I'm trying to:
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.
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.
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);
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With