总体思路:
1.单击Button将对应的值添加到TextView中;
2.设置监听TextView文本的改变;
3.重写TextWatcher中的afterTextChanged()方法,里面实现读取联系人的功能;
4.将TextView中的内容与读取到的联系人号码进行匹配;
5.将符合要求的电话号码显示在ListView中;
6.单击拨号Button或ListView子项拨打电话;
查看官方文档中的TextView可知,addTextChangedListener方法可设置TextView文本内容改变监听器。
addTextChangedListener(TextWatcher watcher)
Adds a TextWatcher to the list of those whose methods are called whenever this TextView's text changes.
当TextView文本内容发生改变时,回调TextWatcher中的afterTextChanged(Editable s)
This method is called to notify you that, somewhere within s
, the text has been changed.
当TextView中的文本发生改变时,读取联系人电话并与TextView中的文本进行匹配子串,将匹配的联系人电话添加到ListView的数据源中:
private StringBuilder textString=new StringBuilder(); //用于修改TextView private StringBuilder textString2=new StringBuilder(); //用于匹配正则表达式
numberText=(TextView)findViewById(R.id.numberText);List<Contacts> mList=new ArrayList<>();
numberText.addTextChangedListener(new TextWatcher(){
@Override
public void afterTextChanged(Editable s) {
mList.clear();
Cursor cursor=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
while(cursor.moveToNext()){
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Contacts contacts=new Contacts(name,number);
Pattern pattern=Pattern.compile("("+textString2.toString()+")"+"+"); //正则表达式 (X)+ 匹配X串1次或1次以上
Matcher matcher=pattern.matcher(number);
if(matcher.find()){
mList.add(contacts);
}
}
adapter.notifyDataSetChanged();
}
单击“*”与单击“#”:
case R.id.numX:
textString.append("*");
textString2.append("\\*");//将“\\*”追加到StringBuilder中时,StringBuilder中内容为“\*”也就是已经将“\\”转义成单个“\”,于是在后面单击退格按钮时,textString2删除的是2个长度而不是3个长度
numberText.setText(textString.toString());
break;
case R.id.numJ:
textString.append("#");
textString2.append("\\#");
numberText.setText(textString.toString());
break;
单击退格Button时的逻辑:
case R.id.back:
if(textString.length()!=0){
if((textString.toString().lastIndexOf("*")!=-1 && textString.toString().lastIndexOf("*")==(textString.length()-1)) || (textString.toString().lastIndexOf("#")!=-1 && textString.toString().lastIndexOf("#")==(textString.length()-1))){
textString.setLength(textString.length()-1);
textString2.setLength(textString2.length()-2); //删除2个字符,多删除或少删会造成正则表达式语法错误
numberText.setText(textString.toString());
}else{
textString.setLength(textString.length()-1);
textString2.setLength(textString2.length()-1);
numberText.setText(textString.toString());
}
}
break;
拨通号码:
case R.id.call:
try{
Intent intent=new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:"+textString.toString()));
startActivity(intent);
}catch(SecurityException e){
e.printStackTrace();
}
break;
demo地址: https://github.com/zycoJamie/Dial