Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

android - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...