【发布时间】:2019-01-12 07:21:46
【问题描述】:
这里有一个显示应用偏好的代码示例。第一个代码是扩展 PreferenceFragment 的类,第二个是扩展 PreferenceActivity 的类。
PreferenceScreen xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key="my_nickname"
android:title="Enter your nickname"
android:summary="Here you need to enter your nickname if you want to change it">
</EditTextPreference>
<ListPreference
android:key="color_key"
android:title="Favorite color"
android:summary="What is your favorite color to change your color preference"
android:entries="@array/favorite_colors"
android:entryValues="@array/colors_numbers"
android:defaultValue="1"/>
<CheckBoxPreference
android:key="notification_key"
android:title="I want to receive a notification"
android:summary="If you check this you will receive a notification"
android:defaultValue="false"/>
</PreferenceScreen>
扩展 PreferenceFragment 类:
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class CustomPreferenceWithFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
扩展 PreferenceActivity 类:
import android.preference.PreferenceActivity;
import android.os.Bundle;
public class CustomActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new CustomPreferenceWithFragment())
.commit();
}
}
问题:
- 扩展 PreferencedFragment 的类的具体工作是什么,扩展 PreferenceActivity 的类的工作是什么?
- android.R.id.content 是什么意思?
- 我知道 Fragment 必须与 Activity 连接,但为什么这里的 Fragment 没有与 Activity 类(扩展 Activity 或 AppCompatActivity)而不是放置在这里的 PreferenceActivity 连接?
【问题讨论】:
-
我认为您不需要 PreferenceActivity 来加载 PreferenceFragment
标签: android preferenceactivity android-sharedpreferences preferencefragment