How to manage dividers in a PreferenceFragment?

后端 未结 10 1025
慢半拍i
慢半拍i 2020-12-01 12:29

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

\"my_preferences\"

10条回答
  •  既然无缘
    2020-12-01 13:06

    I had this exact problem and wanted dividers between preference categories but not between the items themselves. I found that the accepted solution satisfied Question 1 by removing the dividers from preference items but did not fix question 2 and add the dividers between preference categories.

    Fix below. Basically override the onCreateAdapter method of your PreferenceFragmentCompat and give it a custom PreferenceGroupAdapter that has an overridden onBindViewHolder method that uses the position and whatever else you need to set above and below permissions for each view holder. A divider will be drawn when both viewholders allow a divider between them.

    Here is my fix

    public class SettingsFragment extends PreferenceFragmentCompat {
    
        @Override
        protected RecyclerView.Adapter onCreateAdapter(PreferenceScreen preferenceScreen) {
            return new CustomPreferenceGroupAdapter(preferenceScreen);
        }
    
        static class CustomPreferenceGroupAdapter extends PreferenceGroupAdapter {
    
        @SuppressLint("RestrictedApi")
        public CustomPreferenceGroupAdapter(PreferenceGroup preferenceGroup) {
            super(preferenceGroup);
        }
    
        @SuppressLint("RestrictedApi")
        @Override
        public void onBindViewHolder(PreferenceViewHolder holder, int position) {
            super.onBindViewHolder(holder, position);
            Preference currentPreference = getItem(position);
            //For a preference category we want the divider shown above.
            if(position != 0 && currentPreference instanceof PreferenceCategory) {
                holder.setDividerAllowedAbove(true);
                holder.setDividerAllowedBelow(false);
            } else {
                //For other dividers we do not want to show divider above 
                //but allow dividers below for CategoryPreference dividers.
                holder.setDividerAllowedAbove(false);
                holder.setDividerAllowedBelow(true);
            }
        }
    }
    

提交回复
热议问题