我正在尝试替换 MainActivity 中的视图,以便应用程序打开后,我的首选项片段就会出现。一切正常,直到我尝试使用 android.support.v4.app.Fragment 库来支持 API 级别 10 的设备完成相同的任务。在我的 .replace(android.R.id.content, new SettingsFragment()) 调用,我收到以下错误:“FragmentTransaction 类型中的方法 replace(int, Fragment) 不适用于参数 (int, SettingsFragment)”。我不知道为什么这是一个问题,因为我的设置片段扩展了 PreferenceFragment 扩展片段。
非常感谢所有帮助。
public class MainActivity extends FragmentActivity {
@Override
public View onCreateView(String name, Context context, AttributeSet attrs) {
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment()) //SettingFragment is my class that manages the preferences
.commit();
Intent intent = new Intent(this, MainService.class);
startService(intent);
return super.onCreateView(name, context, attrs);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
下一课:
public class SettingsFragment extends PreferenceFragment{
ListPreference notificationDrawerUnitOfMeasurePreference;
ListPreference notificationAreaUnitOfMeasurePreference;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
notificationDrawerUnitOfMeasurePreference = (ListPreference) findPreference("pref_key_measurement_unit");
notificationAreaUnitOfMeasurePreference = (ListPreference) findPreference("pref_key_measurement_unit_notification_area");
notificationDrawerUnitOfMeasurePreference.setOnPreferenceChangeListener(notificationDrawerUnitOfMeasurePreferenceListener);
notificationAreaUnitOfMeasurePreference.setOnPreferenceChangeListener(notificationAreaUnitOfMeasurePreferenceListener);
notificationDrawerUnitOfMeasurePreference.setSummary(notificationDrawerUnitOfMeasurePreference.getValue().toString());
notificationAreaUnitOfMeasurePreference.setSummary(notificationAreaUnitOfMeasurePreference.getValue().toString());
}
private OnPreferenceChangeListener notificationDrawerUnitOfMeasurePreferenceListener = new OnPreferenceChangeListener(){
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
((ListPreference) preference).setValue(newValue.toString());
preference.setSummary(newValue.toString());
return false;
}
};
private OnPreferenceChangeListener notificationAreaUnitOfMeasurePreferenceListener = new OnPreferenceChangeListener(){
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
((ListPreference) preference).setValue(newValue.toString());
preference.setSummary(newValue.toString());
return false;
}
};
}