android listpreference 自定义,在Android中创建ListPreference多选的简单方法?

这里是您需要的所有代码!

public class ListPreferenceMultiSelect extends ListPreference {

//Need to make sure the SEPARATOR is unique and weird enough that it doesn't match one of the entries.

//Not using any fancy symbols because this is interpreted as a regex for splitting strings.

private static final String SEPARATOR = "OV=I=XseparatorX=I=VO";

private boolean[] mClickedDialogEntryIndices;

public ListPreferenceMultiSelect(Context context, AttributeSet attrs) {

super(context, attrs);

mClickedDialogEntryIndices = new boolean[getEntries().length];

}

@Override

public void setEntries(CharSequence[] entries) {

super.setEntries(entries);

mClickedDialogEntryIndices = new boolean[entries.length];

}

public ListPreferenceMultiSelect(Context context) {

this(context, null);

}

@Override

protected void onPrepareDialogBuilder(Builder builder) {

CharSequence[] entries = getEntries();

CharSequence[] entryValues = getEntryValues();

if (entries == null || entryValues == null || entries.length != entryValues.length) {

throw new IllegalStateException(

"ListPreference requires an entries array and an entryValues array which are both the same length");

}

restoreCheckedEntries();

builder.setMultiChoiceItems(entries, mClickedDialogEntryIndices,

new DialogInterface.OnMultiChoiceClickListener() {

public void onClick(DialogInterface dialog, int which, boolean val) {

mClickedDialogEntryIndices[which] = val;

}

});

}

public static String[] parseStoredValue(CharSequence val) {

if ("".equals(val))

return null;

else

return ((String)val).split(SEPARATOR);

}

private void restoreCheckedEntries() {

CharSequence[] entryValues = getEntryValues();

String[] vals = parseStoredValue(getValue());

if (vals != null) {

for (int j=0; j

String val = vals[j].trim();

for (int i=0; i

CharSequence entry = entryValues[i];

if (entry.equals(val)) {

mClickedDialogEntryIndices[i] = true;

break;

}

}

}

}

}

@Override

protected void onDialogClosed(boolean positiveResult) {

// super.onDialogClosed(positiveResult);

CharSequence[] entryValues = getEntryValues();

if (positiveResult && entryValues != null) {

StringBuffer value = new StringBuffer();

for (int i=0; i

if (mClickedDialogEntryIndices[i]) {

value.append(entryValues[i]).append(SEPARATOR);

}

}

if (callChangeListener(value)) {

String val = value.toString();

if (val.length() > 0)

val = val.substring(0, val.length()-SEPARATOR.length());

setValue(val);

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值