我有一个MultiSelectListPreference,显示用户关闭多选对话框时的周数列表我希望使用%s
在摘要中显示所选值,但它仅适用于ListPreference。对此有什么解决方案吗?
<MultiSelectListPreference
android:id="@+id/pref_select_week"
android:defaultValue="@array/week_array_values"
android:entries="@array/week_array"
android:entryValues="@array/week_array_values"
android:icon="@drawable/ic_pref_time"
android:key="keyZodiacSign"
android:summary="%s"
android:title="Select Days" />
答案 0 :(得分:0)
您需要创建MultiSelectListPreference的自定义版本和ovveride getSummary
方法,如下所示:
@Override
public CharSequence getSummary() {
CharSequence cs = super.getSummary();
String summary = cs.toString();
if (summary.contains("%s")) {
String text = "";
StringBuilder builder = new StringBuilder();
CharSequence[] entries = getEntries();
if(entries.length > 0) {
CharSequence[] entryValues = getEntryValues();
Set<String> values = getValues();
int pos = 0;
for (String value : values) {
pos++;
int index = -1;
for (int i = 0; i < entryValues.length; i++) {
if (entryValues[i].equals(value)) {
index = i;
break;
}
}
builder.append(entries[index]);
if (pos < values.size())
builder.append(", ");
}
text = builder.toString();
}
summary = String.format(summary, text);
}
return summary;
}
答案 1 :(得分:0)
至少在Kotlin中,您可以将函数添加到MultiSelectListPreference类中,如下所示:
import android.support.v14.preference.MultiSelectListPreference
fun MultiSelectListPreference.useSelectionAsSummary() {
var summary = ""
for (value in this.values) {
if (summary.isNotEmpty()) {
summary += ", "
}
val i = this.findIndexOfValue(value.toString())
summary += this.entries[i]
}
this.summary = summary
}
用法如下:
prefSelectWeek.useSelectionAsSummary()
答案 2 :(得分:0)
首先向MultiSelectListPreference
添加一个扩展方法,该方法根据所选值设置摘要:
fun MultiSelectListPreference.setSummaryFromValues(values: Set<String>) {
summary = values.map {entries[findIndexOfValue(it)]}.joinToString(", ")
}
然后在onCreateView
中的PreferenceFragmentCompat
:
val columnSelect = findPreference("EXPORT_COLUMNS") as MultiSelectListPreference
columnSelect.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { preference, newValue ->
columnSelect.setSummaryFromValues(newValue as Set<String>)
true
}
columnSelect.setSummaryFromValues(columnSelect.values)