使用片段时,偏好设置不会显示

我试图基于“基本活动”模板添加设置,我试图按照教程进行操作,但是我的首选项没有显示在模拟器屏幕上。这是我在科特林的第二个项目,所以请对我好一点。这是我写的代码:

Main_Activity.kt

   override fun onOptionsItemSelected(item: MenuItem): Boolean {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    return when (item.itemId) {
        R.id.action_settings -> {
            val intent = Intent(this, SettingsActivity::class.java)
            startActivityForResult(intent, RESULT_SETTINGS)
            true
        }
        else -> super.onOptionsItemSelected(item)
    }
}

SettingsActivity.kt

package com.example.travelbuddy

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceFragmentCompat

class SettingsActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)
        supportFragmentManager
            .beginTransaction()
            .replace(R.id.settings_container, SettingsFragment())
            .commit()
    }

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


}

RES /布局/activity_settings.xml

<?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_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/settings_container"
    tools:context=".SettingsActivity">
</FrameLayout>

res / xml / preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory android:title="Photo overlay settings">
        <EditTextPreference
            android:key="font_size"
            android:title="Font size"
            android:summary="Change font size on your photos"
            />
        <ListPreference
            android:key="font_color"
            android:title="Font Color"
            android:entries="@array/fontColors"
            android:entryValues="@array/fontColorsValues"
        />
    </PreferenceCategory>
<!--    <PreferenceCategory android:title="Location Settings">-->
<!--        <SeekBarPreference-->
<!--            android:defaultValue="1"-->
<!--            android:key="reminder_radius"-->
<!--            android:title="Reminder radius"-->
<!--            android:summary="Set the radius of the reminder radar"-->
<!--            />-->
<!--    </PreferenceCategory>-->
</androidx.preference.PreferenceScreen>
评论