PreferenceActivity:不建议使用getFragmentManager()

时间:2018-10-31 07:45:11

标签: android android-fragments android-preferences deprecation-warning androidx

测试android.preference.PreferenceActivity时,出现以下警告:

  

警告:不推荐使用Activity中的[不推荐使用] getFragmentManager()

这就是我获取当前PreferenceFragment的句柄的方式:

FragmentManager fm = this.mActivity.getFragmentManager();
this.currentFragment = (PreferenceFragment) fm.getFragments().get(1);

使用FragmentActivity.getSupportFragmentManager()显然不是一种选择。

找到了PreferenceFragmentCompat,它将替换不推荐使用的PreferenceFragment

但是,androidx是否有PreferenceActivity的替代品?

2 个答案:

答案 0 :(得分:2)

作为设备固件一部分附带的与片段相关的UI类在Android 28中已被弃用。建议移至ActivityFragment的支持库类。 / p>

已经有关于此的其他帖子:

答案 1 :(得分:1)

我想出的是……是AppCompatActivity,它使androidx PreferenceFragment膨胀。我保留了先前的EXTRA_SHOW_FRAGMENT,因此切换到特定的PreferenceFragment仍然可以进行。尚未考虑EXTRA_NO_HEADERS

/**
 * Preference {@link AppCompatActivity}.
 * @see <a href="https://developer.android.com/reference/androidx/preference/Preference Fragment">PreferenceFragment</a>
**/
public final class PreferenceCompatActivity extends AppCompatActivity {

    /** the class-name of the main {@link androidx.preference.PreferenceFragment} */
    public static final String MAIN_FRAGMENT = "com.acme.fragment.PreferencesFragment";

    /** framework {@link Intent} extra */
    public static final String EXTRA_SHOW_FRAGMENT = ":android:show_fragment";

    /** framework {@link Intent} extra */
    public static final String EXTRA_NO_HEADERS = ":android:no_headers";

    /** the currently displayed {@link PreferenceFragment} */
    private PreferenceFragment currentFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String fragmentName = MAIN_FRAGMENT;
        Intent intent = getIntent();
        if (intent.getStringExtra(EXTRA_SHOW_FRAGMENT) != null) {
            fragmentName = intent.getStringExtra(EXTRA_SHOW_FRAGMENT);
        }
        this.switchToFragment(fragmentName, null);
    }

    private void switchToFragment(String fragmentName, @Nullable Bundle args) {
        PreferenceFragment fragment;
        switch(fragmentName) {
            // case "": {break;}
            default: {
                fragment = new PreferencesFragment();
            }
        }
        getFragmentManager().beginTransaction().replace(android.R.id.content, fragment).commit();
        this.currentFragment = fragment;
    }

    @VisibleForTesting(otherwise = VisibleForTesting.NONE)
    public PreferenceFragment getCurrentFragment() {
        return this.currentFragment;
    }

    ...
}