我有一个带有 ListPreference 和 PreferenceScreen 的设置活动。这两个首选项是使用 PreferenceFragment 加载的。单击 PreferenceScreen 时,第二个 PreferenceFragment 会替换第一个 PreferenceFragment,其中包含其他 Preferences 的列表。第二个片段已正确加载但未附加到活动。当我按下后退按钮时,第二个片段正确显示在活动的框架中,这是所需的操作,但在按下后退按钮后实现,而不是在按下 PreferenceScreen 后实现。
这是 SettingsActivity 代码:
public class SettingsActivity extends Activity {
private static String TAG = "SettingsActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false);
setContentView(R.layout.settings);
Log.i(TAG, "SettingsActivity called");
if(findViewById(R.id.fragment_container) != null) {
if(savedInstanceState != null) {
return;
}
getFragmentManager().beginTransaction().add(R.id.fragment_container,
new SettingsFragment()).commit();
}
}
public static class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_preference);
PreferenceScreen ps = (PreferenceScreen) getPreferenceManager().findPreference("nots");
ps.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
SettingsFragment1 sf1 = new SettingsFragment1();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, sf1);
transaction.addToBackStack(null);
//transaction.attach(sf1); this proved to be redundant
transaction.commit();
return true;
}
});
}
}
public static class SettingsFragment1 extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings1_preference);
}
}
}
什么可能是错的?提前致谢