自定义ListPreference

本文介绍了一种在Android应用中实现自定义ListPreference的方法,当用户选择特定选项时会弹出一个输入框供用户输入自定义值,并对输入进行验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要实现在ListPreference弹出的对话框中的某一项选中时,再弹出一个编辑框,具体代码如下:

/**
* @author wu xiang
* @date Dec 26, 2011
* @fileName TestPre.java
*
*/
public class MyListPreference extends ListPreference implements OnPreferenceClickListener {

private Toast myToast;
/**
* @param context
* @param attrs
*/
public MyListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
myToast=Toast.makeText(context, "", Toast.LENGTH_SHORT);
}

public boolean onPreferenceClick(Preference preference) {
// TODO Auto-generated method stub
return false;
}
@Override
protected void onPrepareDialogBuilder(Builder builder) {
int checkItem=getValueIndex(getValue());
builder.setSingleChoiceItems(R.array.pref_search_limit_choices, checkItem, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
if(3==which){
final EditText et=new EditText(MyListPreference.this.getContext());
et.setText(getValue());
new AlertDialog.Builder(MyListPreference.this.getContext())
.setTitle(R.string.setting_title)
.setView(et)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
String sValue=et.getText().toString();
if(Pattern.compile("\\d+").matcher(sValue).matches()){
int iValue=Integer.parseInt(sValue);
if(iValue>0&&iValue<50){
setValue(iValue+"");
}
}else{
myToast.setText(R.string.pref_prompt);
myToast.show();
}
}
})
.setNeutralButton(android.R.string.cancel, null)
.create().show();
}else{
setValue(getEntryValues()[which]+"");
}
dialog.dismiss();
}
});
builder.setPositiveButton(null, null);
}

@Override
protected void onDialogClosed(boolean positiveResult) {

}

private int getValueIndex(String value){
int len=getEntryValues().length;
for(int i=0;i<len;i++){
if(value.equals(getEntryValues()[i])){
return i;
}
}
return 3;//选中“自定义” 一项
}
}


效果如图所示
[img]http://dl.iteye.com/upload/attachment/611782/ce3180a3-b083-3950-a5b8-e0104bb3e983.png[/img]
[img]http://dl.iteye.com/upload/attachment/611784/c9a1fc23-c019-3220-abb5-9b2c0075e83f.png[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值