edittext判断输入字符长度(判断字符串里的中文和字母和数字的长度)转换为char_edittext判断是否少于6位-程序员宅基地

技术标签: edittext  

Android 中的EditText最大可输入字符数可以通过xml文件中为EditText设置maxLength属性或者在代码中为EditText设置LengthFilter来设置。

例如要设置EditText只能输入10个字符

xml中:

 

view plainprint?

  1. <EditText  android:layout_width = "fill_parent"  
  2.     android:layout_height = "wrap_content"  
  3.     android:id = "@+id/mEdit"  
  4.     android:maxLength = "10"/>  

[html] view plaincopyprint?

  1. <EditText  android:layout_width = "fill_parent"  
  2.     android:layout_height = "wrap_content"  
  3.     android:id = "@+id/mEdit"  
  4.     android:maxLength = "10"/>  

 

Html代码 

  1. <EditText  android:layout_width = "fill_parent"  
  2.     android:layout_height = "wrap_content"  
  3.     android:id = "@+id/mEdit"  
  4.     android:maxLength = "10"/>  

代码中:

view plainprint?

  1. EditText mEdit = (EditText)findViewById(R.id.mEdit);  
  2. InputFilter[] filters = {new LengthFilter(10)};  
  3. mEdit.setFilters(filters);  

[java] view plaincopyprint?

  1. EditText mEdit = (EditText)findViewById(R.id.mEdit);  
  2. InputFilter[] filters = {new LengthFilter(10)};  
  3. mEdit.setFilters(filters);  

 

Java代码 

  1. EditText mEdit = (EditText)findViewById(R.id.mEdit);  
  2. InputFilter[] filters = {new LengthFilter(10)};  
  3. mEdit.setFilters(filters);  


以上任意一种方法都可以满足需求,但这种方法只能为EditText设置统一的最大可输入字符,如果碰到根据实际情况限制不同的可输入字符数时,这种方法就不能用了。

比如SIM卡上的电话本姓名字段长度,纯英文下允许输入17个字符,而中文则只可以输入6个字符。此时可以重写InputFilter类来实现。

即:

view plainprint?

  1. EditText mEdit = (EditText)findViewById(R.id.mEdit);          
  2. InputFilter[] filters = {new AdnNameLengthFilter()};  
  3. mEdit.setFilters(filters);  
  4. public static class AdnNameLengthFilter implements InputFilter  
  5.     {  
  6.         private int nMax;  
  7.   
  8.         public  CharSequence filter (CharSequence source, int start, int end, Spanned dest, int dstart, int dend)  
  9.         {  
  10.             Log.w("Android_12", "source("+start+","+end+")="+source+",dest("+dstart+","+dend+")="+dest);  
  11.   
  12.             if(isChinese(dest.toString())|| isChinese(source.toString()))  
  13.             {  
  14.                 nMax = LENGTH_ZNAME;  
  15.             }else  
  16.             {  
  17.                 nMax =LENGTH_ENAME;  
  18.             }  
  19.               
  20.                 int keep = nMax - (dest.length() - (dend - dstart));  
  21.   
  22.                 if (keep <= 0) {  
  23.                     return "";  
  24.                 } else if (keep >= end - start) {  
  25.                     return null; // keep original  
  26.                 } else {  
  27.                     return source.subSequence(start, start + keep);  
  28.                 }  
  29.           
  30.         }  
  31.     }  

[java] view plaincopyprint?

  1. EditText mEdit = (EditText)findViewById(R.id.mEdit);          
  2. InputFilter[] filters = {new AdnNameLengthFilter()};  
  3. mEdit.setFilters(filters);  
  4. public static class AdnNameLengthFilter implements InputFilter  
  5.     {  
  6.         private int nMax;  
  7.   
  8.         public  CharSequence filter (CharSequence source, int start, int end, Spanned dest, int dstart, int dend)  
  9.         {  
  10.             Log.w("Android_12", "source("+start+","+end+")="+source+",dest("+dstart+","+dend+")="+dest);  
  11.   
  12.             if(isChinese(dest.toString())|| isChinese(source.toString()))  
  13.             {  
  14.                 nMax = LENGTH_ZNAME;  
  15.             }else  
  16.             {  
  17.                 nMax =LENGTH_ENAME;  
  18.             }  
  19.               
  20.                 int keep = nMax - (dest.length() - (dend - dstart));  
  21.   
  22.                 if (keep <= 0) {  
  23.                     return "";  
  24.                 } else if (keep >= end - start) {  
  25.                     return null; // keep original   
  26.                 } else {  
  27.                     return source.subSequence(start, start + keep);  
  28.                 }  
  29.           
  30.         }  
  31.     }  

 

Java代码 

  1. EditText mEdit = (EditText)findViewById(R.id.mEdit);          
  2. InputFilter[] filters = {new AdnNameLengthFilter()};  
  3. mEdit.setFilters(filters);  
  4. public static class AdnNameLengthFilter implements InputFilter  
  5.     {  
  6.         private int nMax;  
  7.   
  8.         public  CharSequence filter (CharSequence source, int start, int end, Spanned dest, int dstart, int dend)  
  9.         {  
  10.             Log.w("Android_12", "source("+start+","+end+")="+source+",dest("+dstart+","+dend+")="+dest);  
  11.   
  12.             if(isChinese(dest.toString())|| isChinese(source.toString()))  
  13.             {  
  14.                 nMax = LENGTH_ZNAME;  
  15.             }else  
  16.             {  
  17.                 nMax =LENGTH_ENAME;  
  18.             }  
  19.               
  20.                 int keep = nMax - (dest.length() - (dend - dstart));  
  21.   
  22.                 if (keep <= 0) {  
  23.                     return "";  
  24.                 } else if (keep >= end - start) {  
  25.                     return null; // keep original  
  26.                 } else {  
  27.                     return source.subSequence(start, start + keep);  
  28.                 }  
  29.           
  30.         }  
  31.     }  

其中的isChinese函数是判断是否字符串中是否包含中文字符,具体实现方法就不再赘述了。

LENGTH_ZNAME : 是中文模式下允许输入的最大字符数。

LENGTH_ENAME:是纯英文模式下允许输入的最大字符数。

android怎样判断EditText输入的值是数字还是汉字 ,并限定输入字数

2011-11-25 10:37

判断汉字的方法private boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
             || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
            || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
            || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
            || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
            || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

数字就根据unicode的范围判断吧!

 

方法一:利用TextWatcher


editText.addTextChangedListener(new TextWatcher() {   
           private CharSequence temp;   
           private boolean isEdit = true;   
           private int selectionStart ;   
           private int selectionEnd ;   
           @Override  
           public void beforeTextChanged(CharSequence s, int arg1, int arg2,   
                   int arg3) {   
               temp = s;   
           }   
              
           @Override  
           public void onTextChanged(CharSequence s, int arg1, int arg2,   
                   int arg3) {   
           }   
              
           @Override  
           public void afterTextChanged(Editable s) {   
                selectionStart = editText.getSelectionStart();   
               selectionEnd = editText.getSelectionEnd();   
               Log.i("gongbiao1",""+selectionStart);   
               if (temp.length() > Constant.TEXT_MAX) {   
                   Toast.makeText(KaguHomeActivity.this,   
                           R.string.edit_content_limit, Toast.LENGTH_SHORT)   
                           .show();   
                   s.delete(selectionStart-1, selectionEnd);   
                   int tempSelection = selectionStart;   
                   editText.setText(s);   
                   editText.setSelection(tempSelection);   
               }   
           }   
  
  
       }); 

 private TextWatcher mTextWatcher = new TextWatcher(){
  Toast mToast = null;
  public void beforeTextChanged(CharSequence s, int start, 
    int count,int after) {
  }

  public void onTextChanged(CharSequence s, int start, 
    int before,int count) {
  }
  
  public void afterTextChanged(Editable s) {
   int nSelStart = 0;
   int nSelEnd = 0;
   boolean nOverMaxLength = false;
   
   nSelStart = mEditText.getSelectionStart();
   nSelEnd   = mEditText.getSelectionEnd();
   
   nOverMaxLength = (s.length() > Constants.MAX_TEXT_INPUT_LENGTH) ? true : false;
   if(nOverMaxLength){
    if(null == mToast){
     mToast = Toast.makeText(mContext, 
       R.string.IDS_MSG_TEXT_OVER_MAXLENGTH, 
       Toast.LENGTH_SHORT);
    }
    mToast.show();
    
    s.delete(nSelStart - 1, nSelEnd);

    mEditText.setTextKeepState(s);//请读者注意这一行,保持光标原先的位置,而 mEditText.setText(s)会让光标跑到最前面,

                                                     //就算是再加mEditText.setSelection(nSelStart) 也不起作用
    }
  }
 };

方法二:利用InputFilter

    


editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100)});  //其中100最大输入字数 

editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100)});  //其中100最大输入字数

方法三:在XML中设定

Xml代码 
<EditText  
    .   
    .   
    .   
    Android:maxLength="100"  
/> 

 

=========================================================

方法二:
         利用EditText可以设置filter的特性,自定义一个LengthFilter,当输入字数超过限制时 ,做出自定义的提示
          // 输入框限制输入字数
        InputFilter[] filters = new InputFilter[1];
        filters[0] = new InputFilter.LengthFilter(Constant.TEXT_MAX) {
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                    Spanned dest, int dstart, int dend) {
                if (source.length() > 0 && dest.length() == Constant.TEXT_MAX) {
                    if ((System.currentTimeMillis() - toastTime) > interval) {
                        toastTime = System.currentTimeMillis();
                        Toast
                                .makeText(KaguHomeActivity.this,
                                        R.string.edit_content_limit,
                                        Toast.LENGTH_SHORT).show();
                    }
                }
                if (dest.toString().equals(
                        getResources().getString(R.string.input_default_txt))) {
                    Bundle data = new Bundle();
                    data.putCharSequence("source", source);
                    Message message = textHandler.obtainMessage();
                    message.setData(data);
                    message.sendToTarget();
                }

                return super.filter(source, start, end, dest, dstart, dend);
            }
        };
        editText.setFilters(filters);
private Handler textHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            Bundle data = msg.getData();
            CharSequence source = data.getCharSequence("source");
            editText.setTextColor(Color.BLACK);
            editText.setText(source);
            editText.setSelection(source.length());
        }
    };

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u014644594/article/details/82775881

智能推荐

【Linux】sort排序、uniq去重、wc统计_sort 去重-程序员宅基地

文章浏览阅读2.4w次,点赞9次,收藏56次。文章目录一、sort 排序1、语法2、参数说明3、实例二、uniq 去重1、uniq使用2、sort和uniq去重结果对比三、wc 统计一、sort 排序sort命令用于 对文本文件内容,以行为单位来排序。sort命令以空格作为字段分隔符,将一行分割为多个关键字对文件进行排序。需要注意的是除非你将输出重定向到文件中,否则sort命令并不对文件内容进行实际的排序(即文件内容没有修改),只是..._sort 去重

驱动之路三--------button驱动(input设备)_linux button input-程序员宅基地

文章浏览阅读1.7k次。开发板:smdk6410系统:Linux按键是经常要用的,通过按键产生中断,可以处理不同的功能,键盘的输入就是这么一个原理,键盘也可以作为一个字符设备去写,在 驱动之路二 中就详细阐述过设备分类的概念,也将LED驱动写成了misc设备的,在这要将button驱动基于input设备去写,现在开始写了,先是头文件 s3c_button.h#ifndef __BU_linux button input

SpringBoot2系列一:基础入门_war 包 servletcontextlistener @enablescheduling-程序员宅基地

文章浏览阅读7.1k次。一、概述Spring Boot设计目的是用来简化新Spring应用的初始搭建以及开发过程。Spring Boot并不是对Spring功能上的增强,而是提供了一种快速使用Spring的方式。二、特性 ①创建独立的Spring应用程序 ②嵌入的Tomcat,无需部署WAR文件 ③简化Maven配置 ④自动配置Spring ⑤提供生产就绪型功能,如指标,健康检查和外部配置 ⑥开箱即用,没有代码生成,也无..._war 包 servletcontextlistener @enablescheduling

基于回归分析的股票价格预测_基于varma回归模型的多只股票价格预测模型-程序员宅基地

文章浏览阅读1.6w次,点赞6次,收藏35次。作者:chen_h微信号 &amp; QQ:862251340微信公众号:coderpai介绍由于直接的经济利益,股票价格预测一直吸引着有兴趣投资股票市场和股票交易所的人。它也是金融界的一个重要研究课题。股票市场收益预测是一个非常复杂的问题,取决于公司财务状况和国家政策等诸多因素。这些天股票价格因公司相关新闻,政治,社会经济条件和自然灾害等诸多原因而受到影响。进行了研究以预测股指指数值以..._基于varma回归模型的多只股票价格预测模型

cdh的集成phoenix安装_CDH版Phoenix的安装(图文详解)-程序员宅基地

文章浏览阅读378次。不多说,直接上干货!写在前面的话我这里,四个节点的bigdata集群。分别为cmbigdata1、cmbigdata2、cmbigdata3和cmbigdata4。其中,cmbigdata1即做server,又做agent。cmbigdata2、cmbigdata3和cmbigdata4都是做agent。注意:CDH版本的Phoenix的安装,需要我们自己编译。1、下载2、编译(编译时间较长,耐心..._cdh集成phonix

coding git 初始化与项目远程连接(一)_codon-git-程序员宅基地

文章浏览阅读3.1k次。git 的安装与配置一.git简介 Git是一款免费、开源的分布式版本控制系统。git 的速度很快,对于我们做一些很大的项目来说就方便了很多。二.git 的下载与安装 下载地址:https://git-scm.com/downloads 双击安装包后一直点next就行 安装好后在任意文件夹下右键都能看到这两个选项 说名安装成功三.github用户账户创建 官网_codon-git

随便推点

基础实验篇 | uORB消息读写与自定义实验(二)_uorb通信-程序员宅基地

文章浏览阅读283次。uORB是PX4/Pixhawk系统中非常重要且关键的模块之一,是用于无人机模块间通信的协议机制。本篇将详细介绍uORB并详细拆解uORB消息读写与自定义实验全流程(二)。_uorb通信

Linux----网络编程(IO复用之epoll系统调用函数)_void epoll_add(int epfd, int fd){ struct epoll_eve-程序员宅基地

文章浏览阅读603次。服务器端epoll.c#include &lt;stdio.h&gt;#include &lt;string.h&gt;#include &lt;stdlib.h&gt;#include &lt;assert.h&gt;#include &lt;unistd.h&gt;#include &lt;sys/socket.h&gt;#include &lt;netinet/in.h&g_void epoll_add(int epfd, int fd){ struct epoll_event ev; ev.data.fd = fd; ev

QT5.8.0与VS2013环境配置_vs2013用qt哪个版本-程序员宅基地

文章浏览阅读730次。1、下载VS2013,QT5.8.0,qt-vs-tools-msvc2013-2.1.1。  VS2013版本为:Visual Studio Ultimate 2013 with Update 4 - 简体中文.iso  QT5.8.0版本为:qt-opensource-windows-x86-msvc2013_64-5.8.0.exe,下载地址为:http://download.qt.io/a..._vs2013用qt哪个版本

springMVC视图解析器——InternalResourceViewResolver(转)-程序员宅基地

文章浏览阅读364次。springmvc在处理器方法中通常返回的是逻辑视图,如何定位到真正的页面,就需要通过视图解析器。springmvc里提供了多个视图解析器,InternalResourceViewResolver就是其中之一:最常用的视图解析器:InternalResourceViewResolver当处理器返回“index”时,InternalResourceViewResolver解析器..._springmvc的jsp视图解析器:internalresourceviewresolver

构建虚拟工控环境系列 - 西门子虚拟PLC-程序员宅基地

文章浏览阅读2.1k次。一、 概述跟随着工控安全一路走来,工控安全市场今年明显有相当大的改善,无论从政策还是客户需求,都在逐步扩大中。但是,搞工控安全研究的人员却寥寥无几。一方面工控安全是个跨学课的技术,需要了解多方面的知识,有比较高的技术上的门槛;另一方面,没有可以研究和学习的便利的环境。一般,搞这方面研究的公司或者个人,都会先购买一些硬件设备,搭建一个模拟环境,再做相应的安全研究,成本实在是太高。为了解..._什么是虚拟plc

2023年前端面试题总结_chatgot镜像地址-程序员宅基地

文章浏览阅读1.5k次,点赞21次,收藏25次。如果对你有所帮助还请 收藏谢谢~!关注收藏博客 作者会持续更新…_chatgot镜像地址

推荐文章

热门文章

相关标签