有个小伙伴遇到了这样一个问题,就是AutoCompleteTextView实现自动填充的功能。同时要具备手机格式化的功能。下拉列表最后一行是有个清除历史的功能。可是点击“清除历史”却把文字要设置进去AutoCompleteTextView中。这样的效果显然很糟糕。所以我就写了这样一个简单的demo。来帮助遇到这种问题的朋友解决这样一个问题。二话不多说直接上代码。

  布局文件(activity_main.xml)代码如下: 

  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Please input:" />

  <AutoCompleteTextView
    android:id="@+id/actv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

  </LinearLayout>

  java文件(MainActivity.java)代码如下:

  

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

private AutoCompleteTextView mAutoCompleteTextView;
private String[] mAutoStrs = new String[] { "138 0013 8000", "13800138001",
        "13800138002", "13800138003", "13800138004", "138 0013 800清除记录" };
private String mBeforeTextChangedStr = "";

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.actv);
  ArrayAdapter<String> _arrayAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, mAutoStrs);
  mAutoCompleteTextView.setAdapter(_arrayAdapter);
  mAutoCompleteTextView.setThreshold(1);// 设置输入一个字符就提示
  mAutoCompleteTextView.setOnItemClickListener(new OnItemClickListener() {
     @Override
     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
               long arg3) {
        String _clearStr = "";
        if (arg1 instanceof TextView) {
          _clearStr = ((TextView) arg1).getText().toString();
         }
        if (_clearStr.equals("138 0013 800清楚记录")) {
          mAutoCompleteTextView.setText(mBeforeTextChangedStr);
          Editable _editable = mAutoCompleteTextView.getText();
          Selection.setSelection(_editable, _editable.length());
          Toast.makeText(MainActivity.this, "清除成功了!",
          Toast.LENGTH_LONG).show();
        }
    }
  });

  phoneNumAddSpaceOne(mAutoCompleteTextView);
}

/**
* 手机号格式化代码
*
* @param editText
* EditText对象
*/
public void phoneNumAddSpaceOne(final EditText editText) {
  editText.addTextChangedListener(new TextWatcher() {
    private int start;
    private int before;
    private StringBuilder stringBuilder;

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
                 int count) {
      this.start = start;
      this.before = before;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
      int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
      String _str = s.toString();
      if (!isNumeric(_str.replace(" ", ""))) {
        return;
      }
      mBeforeTextChangedStr = _str;
      // 手机号格式化xxx xxxx xxxx
      if (s == null || s.length() == 0)
        return;
      if (stringBuilder == null) {
        stringBuilder = new StringBuilder();
      } else {
        stringBuilder.delete(0, stringBuilder.length());
      }
      for (int i = 0; i < s.length(); i++) {
      if (i != 3 && i != 8 && s.charAt(i) == ' ') {
        continue;
      } else {
        stringBuilder.append(s.charAt(i));
      if ((stringBuilder.length() == 4 || stringBuilder
        .length() == 9)&& stringBuilder.charAt(stringBuilder.length() - 1) != ' ') {
      stringBuilder.insert(stringBuilder.length() - 1,' ');
      }
    }
  }
  if (!stringBuilder.toString().equals(s.toString())) {
    int index = start + 1;
   if (stringBuilder.charAt(start) == ' ') {
  if (before == 0) {
    index++;
  } else {
    index--;
  }
} else {
  if (before == 1) {
    index--;
  }
}
  editText.setText(stringBuilder.toString());
  editText.setSelection(index);
}
}
});
}

/**
* 判断字符串是否是数字
*
* @param str
* 需要判断的字符串
* @return
*/
public boolean isNumeric(String str) {
  for (int i = str.length(); --i >= 0;) {
    int chr = str.charAt(i);
    if (chr < 48 || chr > 57)
    return false;
    }
    return true;
  }

}

  

android AutoCompleteTextView 实现手机号格式化,附带清空历史的操作的更多相关文章

  1. Xamarin.Android之转换,呼叫,查看历史纪录

    Xamarin.Android之转换,呼叫,查看历史纪录 E文文章. 功能:能将输入的字母转换成相应的数字.并且能呼叫出去.能查看呼叫的历史纪录. 界面代码如下: <?xml version=& ...

  2. Android AutoCompleteTextView和MultiAutoCompleteTextView使用

    Android AutoCompleteTextView和MultiAutoCompleteTextView的功能类似于百度或者Google在搜索栏输入信息的时候,弹出的与输入信息接近的提示信息: 它 ...

  3. [Android Tips] 30.如何在 Android Studio 中一次性格式化所有代码

    在目录上面右击,有 Reformat Code Ctrl + Alt + L 参考 如何在IntelliJ IDEA或Android Studio中一次性格式化所有代码?

  4. Android AutoCompleteTextView控件实现类似百度搜索提示,限制输入数字长度

    Android AutoCompleteTextView 控件实现类似被搜索提示,效果如下 1.首先贴出布局代码 activity_main.xml: <?xml version="1 ...

  5. 九、Android学习第八天——广播机制与WIFI网络操作(转)

    (转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 九.Android学习第八天——广播机制与WIFI网络操作 今天熟悉了An ...

  6. 【转】android Graphics(四):canvas变换与操作

    android Graphics(四):canvas变换与操作 分类: 5.andriod开发2014-09-05 15:05 5877人阅读 评论(18) 收藏 举报   目录(?)[+]   前言 ...

  7. android Graphics(四):canvas变换与操作

    前言:前几篇讲解了有关canvas绘图的一些操作,今天更深入一些,讲讲对画布的操作,这篇文章不像前几篇那么容易理解,如果以前没有接触过画布的童鞋可能比较难以理解,为什么会这样.我尽量多画图,让大家更清 ...

  8. Android EditText手机号格式化输入XXX-XXXX-XXXX

    先来效果图: 设置手机格式化操作只需要设置EditText的addTextChangedListener的监听,下面看代码 /*editText输入监听*/ et_activity_up_login_ ...

  9. Android之计算缓存大小并且清空缓存

    转载博客:http://www.2cto.com/kf/201503/385492.html 项目中碰到了计算缓存大小和清空缓存的功能,这个很常见的功能,几乎每个APP都有,以为实现很简单,网上搜了一 ...

随机推荐

  1. FZU1686 神龙的难题 —— Dancing Links 可重复覆盖

    题目链接:https://vjudge.net/problem/FZU-1686 Problem 1686 神龙的难题 Accept: 812    Submit: 2394 Time Limit: ...

  2. 子元素margin带动父元素拖动

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. 为datanode配置多个数据存储地

    datanode配置多个数据存储地址,涉及到以下两个配置项 dfs.name.dir Determines where on the local filesystem the DFS name nod ...

  4. 枚举子集 Codeforces306 Div2 B

    题目 分析:用二进制法去枚举子集,同时判断满足条件的子集个数加1 #include "iostream" #include "cstdio" using nam ...

  5. sscanf在字符串中的一些使用

    弟弟的作业 你的弟弟刚做完了"100以内数的加减法"这部分的作业,请你帮他检查一下.每道题目(包括弟弟的答案)的格式为a+b=c或者a-b=c,其中a和b是作业中给出的,均为不超过 ...

  6. bzoj4547

    矩阵乘法 看成了合并果子... 就是斐波那契数列,只是有负数的时候,先把负数变成正的,然后矩乘 矩乘还是用单位举矩阵记录快速幂的矩阵比较保险 #include<cstdio> #inclu ...

  7. A. Vanya and Table

    time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standa ...

  8. B - Mike and Fun

    Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u Description Mike a ...

  9. pythonchallenge 2

     pythonchallenge是一个很有意思的学习python的网站,通过用程序解开一个谜,可以进入到下一个level,总共有几十个level,网址是http://www.pythonchallen ...

  10. C++章节练习题

    笔试宝典:http://www.bishibaodian.com/writtenCircle/lightquestionlist http://www.bishibaodian.com/written ...