Loading PreferenceScreen from JAVA
How can we fill PreferenceScreen dynamically (from JAVA).
I have one string array. I want all items to be displayed in second preference screen with checkbox.
Currently I am having
CheckBoxPreferencetags for each item in st开发者_运维技巧ring array in preferences.xml.
Any thoughts on how to do this.
Following code is explained that Implementing the PreferenceActivity Dynamically.Edit in your way.
public class DynamicPreference extends PreferenceActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
ListView listView = new ListView(this);
listView.setId(android.R.id.list);
listView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT, 1));
layout.addView(listView);
this.setContentView(layout);
Preference test1=getPrefereces("key1","Header Preference #1","Summary1",null);
Preference test2=getPrefereces("key2","Header Preference #2","Summary2",null);
PreferenceScreen prefScreen=this.getPreferenceManager().createPreferenceScreen(this);
addPreferenceCategory(prefScreen,"Category",test1,test2);
//addPreferenceCategory(prefScreen,"",test2);
this.setPreferenceScreen(prefScreen);
//add Intent to preferences
Preference prefereces=findPreference("key");
prefereces.setIntent(new Intent(getApplicationContext(), Nextactivity.class));
}
private boolean addPreferenceCategory(PreferenceScreen prefScreen,
String titleCategory, Preference... preferences) {
boolean addPreference = false;
for (Preference preference : preferences) {
if (preference != null)
addPreference = true;
}
if (addPreference) {
PreferenceCategory preferenceCategory = new PreferenceCategory(this);
preferenceCategory.setTitle(titleCategory);
prefScreen.addPreference(preferenceCategory);
for (Preference preference : preferences) {
if (preference != null)
preferenceCategory.addPreference(preference);
}
return true;
} else
return false;
}
private Preference getPrefereces(String key,String title, String summary,
Intent intent) {
// TODO Auto-generated method stub
Preference pref=new Preference(this);
pref.setTitle(title);
pref.setSummary(summary);
if(key!=null)
{
pref.setKey(key);
}
if(intent!=null)
{
pref.setIntent(intent);
}
return pref;
}
}
精彩评论