我想实现一种功能,用户可以使用复选框共享首选项选择要显示的项目组。确切地说,我将从首选项中阅读检查项目并显示。
这是我的偏好类
public class Preferences extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//One way to add default preferences
//addPreferencesFromResource(R.xml.prefs);
//For now I prefer this
setPreferenceScreen(defaultPref());
}
// The first time application is launched this should be read
private PreferenceScreen defaultPref() {
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
CheckBoxPreference checkboxPref = new CheckBoxPreference(this);
checkboxPref.setKey("1");
checkboxPref.setTitle("SomeRandomStuff");
root.addPreference(checkboxPref);
return root;
}
public showAllPreferences () {
// TO SHOW ALL THE PREFERENCES BUT NOT SURE HOW TO DISPLAY THEM
}
}
现在我无法理解如何动态添加更多偏好并在首选屏幕中显示它们。
这是主要的活动类
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.main);
}catch (Exception e) {
e.printStackTrace();
}
exView = (ExpandableListView) findViewById(R.id.expandableListView1);
// STUFF TO ADD IN PREFERENCES
editText = (EditText) findViewById(R.id.editText1);
//BUTTON TO ADD PREFERENCES.(SEARCH TERM IS IDENTIFIED AND ADDED TO PREF)
addButton = (ImageButton) findViewById(R.id.imageButton1);
// BUTTON TO DISPLAY PREFERENCES
prefButton = (ImageButton) findViewById(R.id.imageButtonPref);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = settings.edit();
addButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
PrefObject obj = new PrefObject();
String key = Integer.toString(i);
String title = editText.getText().toString();
//prefArray.add(obj);
editor.putString(key, title);
editor.commit();
i++
}
});
prefButton.setOnClickListener(new OnClickListener() {
// This method should show the preferences activity with new data
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Main.this, Preferences.class);
startActivity(intent);
// I know how to call the intent but I am not sure if
// how to read the saved contents and display it
Preferences pref = new Preferences();
pref.showAllPreferences();
}
});