【问题标题】:How to use PreferenceScreen of Androidx如何使用 Androidx 的 PreferenceScreen
【发布时间】:2019-12-19 08:34:10
【问题描述】:

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

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

接下来,我将 Android-Developers 中的 XML-Code 复制到我的 XML-layout 中并编译了它,但是通过启动活动它中断并出现错误: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>

【问题讨论】:

  • 你能发布你的布局吗?
  • 是的,我可以发布我的布局。有它。
  • 另外,您的 Preference 活动也会有所帮助。

标签: java android xml android-preferences androidx


【解决方案1】:

试试: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>

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

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

【讨论】:

    【解决方案2】:

    java.lang.ClassCastException: 类 androidx.preference.PreferenceScreen 不能转换为 android.view.View
    我的布局:

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

    注意。
    不是布局。

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

    你可以找到所有info here

    您可以定义偏好层次结构。

    注意:根标签必须是&lt;PreferenceScreen&gt;,XML资源必须放在res/xml/ directory中。

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

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

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

    然后将此Fragment 添加到您的Activity,就像添加任何其他`Fragment 一样。

    【讨论】:

      【解决方案3】:

      现在完整的答案:

      1. 将此行添加到您的 App-Gradle:implementation 'androidx.preference:preference:1.1.1'implementation 'androidx.preference:preference-ktx:1.1.1' 对于 Kotlin。并同步 Gradle。创建 res 文件夹中名为 xml 的目录。

      2. 在此目录中创建一个具有您喜欢的名称的 XML 文件,例如 main_preferences。根元素必须是 androidx.preference.PreferenceScreen.

      3. 用您的设置填充 XML 文件,例如:

      <?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. 在文件夹 com.???.??? 的某处创建例如名为MainSettingsFragment 的java 文件。超类(意味着 &lt;Classname&gt; extends &lt;Superclass&gt;)必须是 PreferenceFragmentCompat 并覆盖 onCreatePreferences。您可以复制此代码:
      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. 接下来,有两个选项可以在您的 .
      2. 中实现 PreferencesSreen

      美丽和最好的方法是,它在创建时按代码实现它。 添加您的SettingsActivtyFrameLayout 并给它一个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>
      

      在您的活动代码中,在 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();
          }
      

      或者您在 SettingsActivityXml 中实现 Fragment但我不建议这样做,因为启动活动需要几秒钟

      <?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>
      

      就是这样,玩得开心。

      【讨论】:

      • 感谢本教程,非常清楚。但是,当您说(第 5 点)“在您的 FrameLayout 中添加”时,您可以更清楚地说明您错过了一个词,不是吗?是在您的 main_activity.xml 中添加 FrameLayout 吗?还是在另一个 xml 文件中?
      • 我不断收到“java.lang.NullPointerException:尝试在空对象上调用虚拟方法'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)'参考”并且仅当我取消注释该行时:“setPreferencesFromResource(R.xml.settings, rootKey);”并且 xml 看起来不错
      • 谢谢你,克里斯蒂安。无意间评论了。现在我已经修好了
      • Pete,您在哪里以及为什么使用 RecyclerView?我不认为这是因为我的代码。也许你检查你的 RecyclerView 适配器和它的初始化 ;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      相关资源
      最近更新 更多