android - showing listView in PreferenceActivity

折月煮酒 提交于 2020-01-03 05:04:50

问题


i wish to show a listView on a PreferenceActivity similar to what the android OS wifi-settings has for the list of networks (example here , on the bottom area of the image) . however , such a thing isn't availabe , so i've created a new class that extends Preference , and what i returned in the onCreateView is just a ListView instance .

it worked , but the listView has a constant size of about a single item no matter what i do to its layoutParams and no matter what i do to the adapter . even if i set the adapter inside the onCreateView , it has the exact same size .

not only that , but the listView cannot be scrolled , even though it is clear that it has multiple items within it .

i would , of course, want to use the same text size standard as on all of the preferences , to give a native feeling.

can anyone please tell me what can be done in order to make it work well?

btw, the app should work for android API 10+ (minimum 10) .


回答1:


In case you are going for the same appearance / behavior, you should stay with the plain PreferenceActivity implementation, and add the new preference items into the "list" dynamically from code (eventually with custom renderers).

A basic implementation of such display would be:

/**
 * This variable stands for the items with which you want to populate the list
 */
final HashMap<String, String> networks = new HashMap<String, String>();

final PreferenceCategory cat = new PreferenceCategory(getApplicationContext());
cat.setTitle(R.string.wifinetworks); // holding "Wi-fi networks"
for (final String networkTitle : networks.keySet())
{
    final Preference pref = new Preference(getApplicationContext());
    pref.setTitle(networkTitle);
    pref.setSummary(networks.get(networkTitle));
    cat.addPreference(pref);
}

Edit: For adding custom components to an existing PreferenceActivity, you should give a try to the addContentView method. From within onCreate:

final LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, 
        LayoutParams.WRAP_CONTENT);
addContentView(buttonBar, params);



回答2:


ok , the answer would be to use setContentView to whatever layout you wish (including any views you wish) , add there a listView for the preferences , and for this listView , call bind and setAdapter.

i've found this solution by looking at other solutions, like this one: http://kmansoft.com/2011/08/29/implementing-long-clickable-preferences/



来源:https://stackoverflow.com/questions/10616317/android-showing-listview-in-preferenceactivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!