问题
I need to show a list in Preferences view, so I created my own class (inherit of Preference
) and then set it like this:
@Override
protected View onCreateView(ViewGroup parent){
cards = new ArrayList<String>();
// Test
cards.add("4859-2368957415");
cards.add("4859-5987412598");
LinearLayout layout = new LinearLayout(getContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
list = new ListView(getContext());
list.setLayoutParams(params);
layout.addView(list);
adapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_list_item_1, cards);
list.setAdapter(adapter);
return layout;
}
This works, but I can't scroll it (it shows really tiny). I think that my Listview is embed into a Preference (with its own width and height by default), but I need to show a completely list.
How can I achieve it? Thanks!
回答1:
I solved my own problem adding PreferenceScreen
dynamically instead of embedding a ListView
component into a Preference
.
findPreference("addmyaccount").setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
// Get preference category and add a custom preference (simulating a ListView)
PreferenceCategory targetCategory = (PreferenceCategory)findPreference("myaccounts");
final Preference account = new Preference(Settings.this);
account.setKey("mykey");
account.setTitle("Custom Preference");
targetCategory.addPreference(account);
editor.putString("mykey", "Custom Preference");
editor.commit();
}
});
来源:https://stackoverflow.com/questions/9947539/embed-listview-into-preferences-in-android