我正在尝试在Android应用中实施基本设置活动,并获得空白屏幕或崩溃。我见过的文档和样本没有帮助,因为它们要么旧又不一致。例如,根据您查看的位置,设置活动应该扩展Activity,PreferenceActivity或AppCompatPreferenceActivity(文件>新>活动>设置活动)的一部分。
developer.android.com说你应该实现以下内容:
public class SettingsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}
然而,在Android Studio中使用的“设置活动”不会对其创建的三个片段中的任何一个进行此调用。它使用首选项标题。
所以这是我的问题:
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit()
答案 0 :(得分:2)
比方说,我们想要一个带有一个复选框首选项片段的设置屏幕,如下所示:
这是有关如何建立设置活动的分步指南,您可以在其中添加一些首选项来切换或更改Android应用程序的配置:
在build.gradle
模块的app
文件中添加用于支持首选项片段的依赖项:
dependencies {
compile 'com.android.support:preference-v7:25.1.0'
}
在xml
目录中添加res
Android资源目录。
在xml
目录中,添加一个名为XML resource file
的新pref_visualizer.xml
,如下所示。我们将在其中添加一个复选框首选项片段。
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:defaultValue="true"
android:key="show_base"
android:summaryOff="Bass will not be shown currently."
android:summaryOn="Bass will be shown currently."
android:title="Show Bass"
/>
</PreferenceScreen>
PreferenceScreen
是根标记,可以容纳任意数量的首选项片段。如果要添加更多类型列表或文本框的配置,则需要在此处将其作为PreferenceScreen
标签的子元素添加。
添加一个名为SettingsFragment
的新Java类,它将承载PreferenceScreen
。它应该扩展PreferenceFragmentCompat
类,如下所示:
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.support.v7.preference.CheckBoxPreference;
import android.support.v7.preference.EditTextPreference;
import android.support.v7.preference.ListPreference;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.support.v7.preference.PreferenceScreen;
import android.widget.Toast;
public class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle bundle, String s) {
addPreferencesFromResource(R.xml.pref_visualizer);
}
}
现在是最后一部分,我们将在应用程序中的活动与托管SettingsFragment
的{{1}}类之间建立关联。添加一个名为PreferenceScreen
的新活动,该活动继承自SettingsActivity
类。 AppCompatActivity
类将充当SettingsActivity
的容器。
PreferenceScreen
的Java文件:
SettingsActivity
<{> import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
}
的布局文件如下所示(SettingsActivity
)。这里的activity_settings.xml
属性是症结所在。它将此活动连接到整个项目中存在的任何从android.name
类继承的类。我只有一个这样的类,名为PreferenceFragmentCompat
。如果您的应用具有多个设置屏幕,则您可能有多个类继承自SettingsFragment
类。
PreferenceFragmentCompat
您都准备好了!
答案 1 :(得分:1)
SettingsActivity应该扩展哪个类?
对我有用的是AppCompatActivity
。{/ p>
static final String ANIMATION = "animation" ;
static final String COUNTDOWN_ON_OFF = "countdown_on_off";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getFragmentManager().findFragmentById(android.R.id.content) == null)
{
getFragmentManager().beginTransaction().add(android.R.id.content, new Prefs()).commit();
}
}
我删除了与首选项标题相关的所有生成代码,并为我的PreferenceFragment
public static class Prefs extends PreferenceFragment
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
// findPreference() uses android:key like in preferences.xml !
bindPreferenceSummaryToValue(findPreference(ANIMATION));
}
}
我的Activity
类中的静态方法(改编自模板)。您可能想要检查其他偏好类型:
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference)
{
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
if (preference instanceof CheckBoxPreference)
{
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getBoolean(preference.getKey(), true));
}
else
{
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
}
最后,Preference.OnPreferenceChangeListener
中的Activity
作为静态变量(也改编自模板):
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.<br>
* template by Android Studio minus Ringtone Preference
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object value)
{
String stringValue = value.toString();
if (preference instanceof ListPreference)
{
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
}
else if (preference instanceof RingtonePreference)
{
// my app didn't need that
return true;
}
else if (preference instanceof CheckBoxPreference)
{
Context ctx = preference.getContext();
boolean isChecked = (Boolean) value;
if (preference.getKey().equals(ANIMATION))
{
preference.setSummary(isChecked ? ctx.getString(R.string.sOn) : ctx.getString(R.string.sOff));
}
else if (preference.getKey().equals(COUNTDOWN_ON_OFF))
{
preference.setSummary(isChecked ? ctx.getString(R.string.sWhenPaused) : ctx.getString(R.string.sNever) );
}
}
else
{
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
}
答案 2 :(得分:1)
在Kotlin和android-x上:
等级:
implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
implementation 'androidx.core:core-ktx:1.2.0-alpha02'
implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta2'
implementation 'com.google.android.material:material:1.1.0-alpha08'
implementation "androidx.preference:preference-ktx:1.1.0-rc01"
implementation 'androidx.core:core-ktx:1.2.0-alpha02'
implementation 'androidx.collection:collection-ktx:1.1.0'
implementation 'androidx.fragment:fragment-ktx:1.2.0-alpha01'
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null)
supportFragmentManager.commit { replace(android.R.id.content, PrefsFragment()) }
}
class PrefsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
}
}
}
preferences.xml
<androidx.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<androidx.preference.Preference android:title="hello"/>
</androidx.preference.PreferenceScreen>