Androidx的PreferenceScreen使用方法

How to use PreferenceScreen of Androidx

我的问题是我想向我的应用程序添加一个 PreferenceScreen,但我无法使用它,我也不知道为什么。

我实现了库 androidx.preference:preference:1.1.0-rc01。然后我想将 PreferenceScreen 添加到我的 XML-layout,但它没有提出任何建议。

接下来,我将 XML-代码从 Android-Developers 复制到我的 XML-layout 中并编译它,但是通过启动 activity 它中断了错误:java.lang.ClassCastException: class androidx.preference.PreferenceScreen cannot be cast to android.view.View

有人可以帮助我正确使用 androidx.preference.PreferenceScreen 吗?

我的布局:

<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent">
    <androidx.preference.SwitchPreference
        android:defaultValue="true"
        android:key="example_switch"
        android:summary="Turn this option on or off"
        android:title="Settings option" />
</androidx.preference.PreferenceScreen>

尝试:xml/preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen  
  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent">
    <SwitchPreference
        android:defaultValue="true"
        android:key="example_switch"
        android:summary="Turn this option on or off"
        android:title="Settings option" />
</PreferenceScreen>

我也更喜欢使用由我的 activity 托管的偏好片段。

class MySettingsActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportFragmentManager
                .beginTransaction()
                .replace(R.id.settings_container, SettingsFragment())
                .commit()
    }
}
class SettingsFragment : PreferenceFragmentCompat() {
    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.preferences, rootKey)
    }
}

java.lang.ClassCastException: class androidx.preference.PreferenceScreen cannot be cast to android.view.View
My Layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen>
...
</androidx.preference.PreferenceScreen>

关注
不是布局。

Can somebody help me to use the androidx.preference.PreferenceScreen correctly?

您可以找到所有 info here.

您可以定义首选项层次结构。

Caution: The root tag must be a <PreferenceScreen>, and the XML resource must be placed in the res/xml/ directory.

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

    ....

</PreferenceScreen>

要从 XML 属性扩展层次结构,请创建一个 PreferenceFragmentCompat, override onCreatePreferences(),并提供 XML 资源:

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

然后将此 Fragment 添加到您的 Activity 中,就像添加任何其他“片段”一样。

现在完整答案:

  1. Add this line to your App-Gradle: implementation 'androidx.preference:preference:1.1.1' or implementation 'androidx.preference:preference-ktx:1.1.1' for Kotlin. And sync Gradle. Create a Directory named xml in res Folder.

  2. Create in this directory an XML-File with your prefered name for example main_preferences. Root Element must be androidx.preference.PreferenceScreen.

  3. Fill XML-File with your settings for example:

<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent">
    <androidx.preference.SwitchPreference
        android:defaultValue="true"
        android:key="example_switch"
        android:summary="Turn this option on or off"
        android:title="Settings option" />
</androidx.preference.PreferenceScreen>
  1. Create somewhere in the folder com.???.??? a java file for example named MainSettingsFragment. Superclass (means <Classname> extends <Superclass>) must be PreferenceFragmentCompat and override onCreatePreferences. You can copy this code:
import android.os.Bundle; 
import androidx.preference.PreferenceFragmentCompat;
import com.???.???.R;

public class <YourClassname> extends PreferenceFragmentCompat {
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        // Load the preferences from an XML resource
        setPreferencesFromResource(R.xml.<yourXmlFilename>, rootKey);
    }
}
  1. Next, there are two options to implement the PreferencesSreen in your .

最好的方法是,在创建时按代码实现它。 在你的 SettingsActivty 中添加一个 FrameLayout 并给它一个 ID,例如 fl_main_settings:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/<!-- yourID -->">

</FrameLayout>

并且在您的 Activity 代码中,确实在 onCreate 方法的顶部添加了这个:

package com.???.???;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Html;
import android.view.MenuItem;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.text.HtmlCompat;

import com.???.???.MainSettingsFragment;
public class SettingsActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.<SettingsActivityXML(with the FrameLayout)>);

        //If you want to insert data in your settings
        <YourSettingsFragmentClass> settingsFragment = new <YourSettingsFragmentClass>();
        settingsFragment. ...
        getSupportFragmentManager().beginTransaction().replace(R.id.<YourFrameLayout>,settingsFragment).commit();
        
        //Else
        getSupportFragmentManager().beginTransaction().replace(R.id.<YourFrameLayout>,new <YourSettingsFragmentClass>()).commit();
    }

您在设置ActivityXml中实现了一个Fragment但我不推荐这样做,因为启动 activity 需要几秒钟:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false">

    <fragment
        android:tag="frag"
        android:name="com.quickme.musicme.Fragments.MainSettingsFragment"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
</LinearLayout>

就是这样,玩得开心。