将Listview嵌入到Android中的首选项中

时间:2012-03-30 17:16:44

标签: android android-listview android-preferences

我需要在Preferences视图中显示一个列表,所以我创建了自己的类(继承了Preference),然后像这样设置:

@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; 
}

这有效,但我无法滚动它(它显示非常小)。我认为我的Listview嵌入了一个Preference(默认情况下有自己的宽度和高度),但我需要显示一个完整的列表。

我怎样才能实现它?谢谢!

1 个答案:

答案 0 :(得分:1)

我解决了自己的问题,动态添加PreferenceScreen而不是将ListView组件嵌入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();

    }
});