繁体   English   中英

Android MultiSelectListPreference的优先顺序

[英]Android MultiSelectListPreference with priority order

我是Android新手。 我想在我的情况下使用MultiSelectListPreference。

但是我遇到一个问题:我的列表需要保持元素的顺序。 假设有5个元素:

0 - Tom
1 - David
2 - Bob
3 - Mary
4 - Chris

并且用户选择0、2、3。然后列表的顺序必须如下:

汤姆,鲍勃,玛丽

但是MultiSelectListPreference将设置存储在Set<String> ,而不是ArrayList<String> ,因此由于Set ,因此不确定此顺序。

如何确定此订单? 谢谢。

camdaochemgio,即使在您进行编辑之前,我也了解您的问题。

由于我们正在谈论的是一个Set(存储唯一值),因此此getValues()函数需要输入到您自己的revertValues函数中,该函数根据您的数据预置将值转换为索引。 我索要您的代码,以便通过使用自己的样式/术语编写解决方案来表达自己。

解决方案:

我在MultiSelectListPreference的文档中注意到以下方法:

int findIndexOfValue(String value)

但是您不存储对对象的此类引用,因此我创建了此类以扩展MultiSelectListPreference(在新文件中!):

public class DataHolder extends MultiSelectListPreference {

    // note: AttributeSet  is needed in super class
    public DataHolder(Context context,AttributeSet attrs) {   
        super(context, attrs);

        List<CharSequence> entries = new ArrayList<CharSequence>();
        List<CharSequence> entriesValues = new ArrayList<CharSequence>();

        /** We could use the String Array like you did in your Q, 
         * But I preffer this way of populating data - 
         * It keeps things open and unlimitted.
         * If you really want the data picked up from the xml , just use : 
         * context.getResources().getStringArray(R.array.entries)  and
         * context.getResources().getStringArray(R.array.entryValues) 
         * */

        entries.add("0");
        entries.add("1");
        entries.add("2");
        entries.add("3");
        entries.add("4");
        entriesValues.add("Tom");
        entriesValues.add("David");
        entriesValues.add("Bob");
        entriesValues.add("Mary");
        entriesValues.add("Chris");

        setEntries(entries.toArray(new CharSequence[5]));
        setEntryValues(entriesValues.toArray(new CharSequence[5]));
    }
}

现在我们需要将其插入您的监听器中。 在您的SettingsFragment类中,只需添加一个新字段:

private DataHolder dh = null;

并更改构造函数以接受并初始化它:

public SettingsFragment(Context c) {
    dh = new DataHolder(c,null);
}

下一步:从xml中删除对数据的引用。 现在看起来应该像这样:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    <com.example.multiselectpref.DataHolder
        android:key="pref_key_name_choice"
        android:title="@string/name_choice"
    />
</PreferenceScreen>

返回监听器,在onSharedPreferenceChanged方法中,您可以将Toast更改为:

toast_message += (dh.findIndexOfValue(name) + ": "+name+"    , ");

为我工作..(提交到fork @ https://github.com/li3ro/MultiSelectPref的代码)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM