我正试图从我的应用程序设置(preferences.xml)中的布局中检索SeekBarPreference。然而,当我试图将findPreference("font_size")转换为SeekBarPreference时,我遇到了以下错误:
无法转换类型;不能将android.preference.Preference转换为androidx.preference.SeekBarPreference 以下是对应于我的设置页面(MyPreferencesAcitivty.java)的代码 - 错误发生在此行:“final SeekBarPreference fontSizeSeekBar = (SeekBarPreference) findPreference("font_size");”:
以下是我的设置页面布局(
无法转换类型;不能将android.preference.Preference转换为androidx.preference.SeekBarPreference 以下是对应于我的设置页面(MyPreferencesAcitivty.java)的代码 - 错误发生在此行:“final SeekBarPreference fontSizeSeekBar = (SeekBarPreference) findPreference("font_size");”:
package com.example.myapplication;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.Preference;
import android.widget.EditText;
import androidx.preference.SeekBarPreference;
public class MyPreferencesActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment
{
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// Retrieve the EditTextPreference demonstrating the font size
final EditTextPreference fontSizeEditPreference = (EditTextPreference) findPreference("font_size_edittext");
// Retrive the EditText component of the EditTextPreference
final EditText fontSizeEditText = fontSizeEditPreference.getEditText();
// Attach a listener to the font size seekbar (changes the size of the EditText)
final SeekBarPreference fontSizeSeekBar = (SeekBarPreference) findPreference("font_size");
}
}
}
以下是我的设置页面布局(
preferences.xml
)的XML代码:<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.kizitonwose.colorpreference.ColorPreference
android:defaultValue="#FF8983"
android:title="Addition Highlight Color"
app:colorChoices="@array/highlight_colors"
android:key="addition_highlight_color"/>
<com.kizitonwose.colorpreference.ColorPreference
android:defaultValue="#99ffcc"
android:title="Removal Highlight Color"
app:colorChoices="@array/highlight_colors"
android:key="removal_highlight_color"/>
<SeekBarPreference
android:key="font_size"
android:title="Font Size"
android:min="12"
android:max="32"
android:defaultValue="14" />
<EditTextPreference
android:defaultValue="Default Value"
android:key="font_size_edittext"
android:selectAllOnFocus="true"
android:singleLine="true"
android:title="A" />
</PreferenceScreen>
我已将以下实现包含在我的gradle (app-level)中:
implementation 'androidx.preference:preference:1.0.0'