使用androidx.preference.PreferenceScreen和PreferenceScreen之间的区别

我的应用程序针对API 28并且具有最低API 15.作为支持库,我使用的是
AndroidX.

我有一个由活动托管的偏好片段,如下所示:

SettingsFragment.java

package com.example.app;

import android.os.Bundle;

import androidx.preference.PreferenceFragmentCompat;

public class SettingsFragment extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preferences, rootKey);

    }
}

SettingsActivity.java

package com.example.app;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
    }
}

这是SettingsFragment.java使用的XML布局

的preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <SwitchPreference
        android:defaultValue="false"
        android:key="pref_switch"
        android:title="@string/switch" />
</PreferenceScreen>

作为首选层次结构的根,我应该使用PreferenceScreen或androidx.preference.PreferenceScreen来实际向后兼容布局(使用AndroidX)吗?两者有什么区别?什么是最佳做法?

最佳答案 从
the docs开始:

AndroidX is the open-source project that the Android team uses to
develop, test, package, version and release libraries within 07001.

AndroidX is a major improvement to the original Android 07002. Like the Support Library, AndroidX ships separately from the
Android OS and provides backwards-compatibility across Android
releases. AndroidX fully replaces the Support Library by providing
feature parity and new libraries. In addition AndroidX includes the
following features:

  • All packages in AndroidX live in a consistent namespace starting with the string androidx. The Support Library packages have been
    mapped into corresponding androidx.* packages. For a full mapping of
    all the old classes and build artifacts to the new ones, see the
    07003 page.

所以简单来说,它是新的库,您应该使用而不是支持库,因为它具有最新的组件和功能.

因此,您的PreferenceScreen与androidx.preference.PreferenceScreen相同,但与不同的包装器捆绑在一起.

点赞