Как удалить левый отступ в PreferenceScreen? - программирование
Подтвердить что ты не робот

Как удалить левый отступ в PreferenceScreen?

Поскольку PreferenceFragment устарел, я использую PreferenceFragmentCompat.

После замены фрагмента я получаю отступ от содержимого.
After replacing the fragment, I get left indentation from the content.

Отступы, скорее всего, появляются из-за значков, но я ими не пользуюсь (по умолчанию значок отсутствует).

Я пытался установить атрибут значка android:icon="@null" или android:color/transparent, но это не помогло.

Функция замены фрагмента:

private fun replaceFragment(fragment: Fragment) {
    supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_layout, fragment)
            .commit()
}

content_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/app_bar_main">

    <FrameLayout
        android:id="@+id/fragment_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Фрагмент моих настроек:

class SettingsFragment : PreferenceFragmentCompat() {

companion object {

    /**
     * A preference value change listener that updates the preference summary
     * to reflect its new value.
     */
    private val sBindPreferenceSummaryToValueListener = Preference.OnPreferenceChangeListener { preference, value ->

        val stringValue = value.toString()

        if (preference is ListPreference) {
            // For list preferences, look up the correct display value in
            // the preference 'entries' list.
            val index = preference.findIndexOfValue(stringValue)

            // Set the summary to reflect the new value.
            preference.setSummary(
                    if (index >= 0)
                        preference.entries[index]
                    else
                        null)

        } else {
            // For all other preferences, set the summary to the value's
            // simple string representation.
            preference.summary = stringValue
        }
        true
    }
}

override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
    setPreferencesFromResource(R.xml.preferences, rootKey)

    /**
     * Bind preference summary to value for lists and sorting list preferences
     */

    bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_key_name)))
    bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_key_language)))

}

private fun bindPreferenceSummaryToValue(preference: Preference) {
    // Set the listener to watch for value changes.
    preference.onPreferenceChangeListener = sBindPreferenceSummaryToValueListener

    // Trigger the listener immediately with the preference's
    // current value.
    sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
            PreferenceManager
                    .getDefaultSharedPreferences(preference.context)
                    .getString(preference.key, ""))
}

preferences.xml

<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<android.support.v7.preference.PreferenceCategory android:title="@string/pref_header_general">

    <android.support.v7.preference.EditTextPreference
        android:defaultValue="@string/nav_header_subtitle"
        android:key="@string/pref_key_name"
        android:summary="@string/nav_header_subtitle"
        android:title="@string/pref_title_your_name" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="true"
        android:key="@string/pref_key_sound"
        android:summary="@string/pref_summary_sound"
        android:title="@string/pref_title_sound" />

    <android.support.v7.preference.ListPreference
        android:dialogTitle="Select language"
        android:entries="@array/settings_list_preference_languages_titles"
        android:entryValues="@array/settings_list_preference_languages_values"
        android:key="@string/pref_key_language"
        android:summary="Click to select language"
        android:title="Language" />

</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/pref_header_notifications">

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="true"
        android:key="@string/notifications_new_message"
        android:title="@string/pref_title_new_notification_sound" />


    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="true"
        android:key="@string/pref_key_notifications_vibrate"
        android:summary="@string/pref_summary_vibrate"
        android:title="@string/pref_title_vibrate" />

</android.support.v7.preference.PreferenceCategory>

<!--Account Settings-->
<android.support.v7.preference.PreferenceCategory android:title="@string/pref_header_account">

    <android.support.v7.preference.Preference
        android:key="@string/pref_key_logout"
        android:title="@string/pref_title_logout" />

    <android.support.v7.preference.Preference
        android:key="@string/pref_key_delete_account"
        android:title="@string/pref_title_delete_account" />
</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/pref_header_about">

    <android.support.v7.preference.Preference
        android:summary="@string/app_version"
        android:title="@string/pref_title_version" />

</android.support.v7.preference.PreferenceCategory>

styles.xml

<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">?themePrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="themePrimary">@color/colorPrimary</item>

    <!-- PreferenceFragmentCompat -->
    <item name="preferenceTheme">@style/PreferenceThemeOverlay.v14.Material</item>
</style>

Версия SDK

ext.support_version = '28.0.0-rc01'
4b9b3361

Ответ 1

Если вы перенесете свой код на androidx, вы можете легко удалить дополнительные отступы, добавив следующее к каждому предпочтению:

app:iconSpaceReserved="false"

Вам также необходимо добавить следующее пространство имен в начало вашего XML файла:

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

Ответ 2

Поместите файл values-preference.xml в res/values-sw360dp:

<?xml version="1.0" encoding="utf-8"?>

<resources xmlns:tools="http://schemas.android.com/tools">
    <bool name="config_materialPreferenceIconSpaceReserved"
          tools:ignore="MissingDefaultResource,PrivateResource" >
        false
    </bool>
</resources>

При просмотре библиотечного кода вы можете увидеть, что у него есть файл ресурсов в sw360dp-v13, который переопределяет ваши базовые модификации, такие как app:iconSpaceReserved="false".