TextWatcher学习[通俗易懂]

xmlversion=”1.0″encoding=”utf-8″?>LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”android:orientation=”vertical”android:layout_width=”fill_parent”android:layout_heig

大家好,又见面了,我是你们的朋友全栈君。<?
xml version=”1.0″ encoding=”utf-8″
?>


<
LinearLayout
 
xmlns:android
=”http://schemas.android.com/apk/res/android”

android:orientation

=”vertical”

android:layout_width

=”fill_parent”

android:layout_height

=”fill_parent”



>


<
TextView
 
android:id
=”@+id/tv”

android:layout_width

=”fill_parent”
 

android:layout_height

=”wrap_content”
 

android:textColor

=”@android:color/white”
 

android:ellipsize

=”marquee”
 

android:focusable

=”true”
 

android:marqueeRepeatLimit

=”marquee_forever”
 

android:focusableInTouchMode

=”true”
 

android:scrollHorizontally

=”true”
 

android:text

=”Please input the text:”



/>


<
EditText
 
android:id
=”@+id/ET”
 

android:layout_width

=”match_parent”
 

android:layout_height

=”wrap_content”

android:inputType

=”number”
/>


</
LinearLayout
>

Java代码:
package com.android.text;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TextWatcherDemo extends Activity {

    private TextView mTextView;
    private EditText mEditText;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mTextView = (TextView)findViewById(R.id.tv);
        mEditText = (EditText)findViewById(R.id.ET);
        mEditText.addTextChangedListener(mTextWatcher);
    }
    TextWatcher mTextWatcher = new TextWatcher() {

        private CharSequence temp;
        private int editStart ;
        private int editEnd ;
        @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) {

            mTextView.setText(s);
        }
      
        @Override
        public void afterTextChanged(Editable s) {

            editStart = mEditText.getSelectionStart();
            editEnd = mEditText.getSelectionEnd();
            if (temp.length() > 10) {

                Toast.makeText(TextWatcherDemo.this,
                        “你输入的字数已经超过了限制!”, Toast.LENGTH_SHORT)
                        .show();
                s.delete(editStart-1, editEnd);
                int tempSelection = editStart;
                mEditText.setText(s);
                mEditText.setSelection(tempSelection);
            }
        }
    };
}
(2)使用

TextWathcer实现EditeText和TextView同步


TextWatcher自身是一个接口,首先需要实现这个接口并覆盖其三个方法,分别为Text改变之前,改变之后以及改变的过程中各自发生的动作相应,这里我们只需要实现EditText在文本发生改变时候让TextView的内容跟着发生变化。

editText.addTextChangedListener(new TextWatcher(){

@Override  
public void afterTextChanged(Editable s) {  
    }  
@Override  
public void beforeTextChanged(CharSequence s,int start,int count,int after){      
    }  
@Override  
public void onTextChanged(CharSequence s, int start, int before, int count) {  
   textView.setText(editText.getText());  
  }  
}); 

可以看出TextWatcher是专门用来监听文本变化的,正因为它的这个技能,正是我们实现同步的功能所需要的











Android的编辑框控件EditText在平常编程时会经常用到,有时候会对编辑框增加某些限制,如限制只能输入数字,最大输入的文字个数,不能输入 一些非法字符等,这些需求有些可以使用android控件属性直接写在布局xml文件里,比如android:numeric=”integer”(只允 许输入数字);

     对于一些需求,如非法字符限制(例如不允许输入#号,如果输入了#给出错误提示),做成动态判断更方便一些,而且容易扩展;

     在Android里使用TextWatcher接口可以很方便的对EditText进行监听;TextWatcher中有3个函数需要重载:

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);

     从函数名就可以知道其意思,每当敲击键盘编辑框的文字改变时,上面的三个函数都会执行,beforeTextChanged可以给出变化之前的内容,onTextChanged和afterTextChanged给出追加上新的字符之后的文本;

所以对字符的限制判断可以在afterTextChanged函数中进行,如果检查到新追加的字符为认定的非法字符,则在这里将其delete掉,那么他就不会显示在编辑框里了:

private final TextWatcher mTextWatcher = new TextWatcher() { 

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) {

 if (s.length() > 0) { int pos = s.length() – 1; char c = s.charAt(pos); if (c == ‘#’) {//这里限制在字串最后追加# s.delete(pos,pos+1); Toast.makeText(MyActivity.this, “Error letter.”,Toast.LENGTH_SHORT).show(); }

 } }};

     注册监听:

EditText mEditor = (EditText)findViewById(R.id.editor_input); 

mEditor.addTextChangedListener(mTextWatcher);


转载地址:http://czhjchina.blog.163.com/blog/static/2002790472012220113455325/

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/125623.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • rownumber实现分页的方法

    rownumber实现分页的方法利用rownumer实现分页的两种常用方式:1)利用betweendeclare@pagesizeintset@pagesize=4declare@pageindexintset@pageindex=3 select *from(s

  • Failed to find Platform SDK with path: platforms;android-30「建议收藏」

    Failed to find Platform SDK with path: platforms;android-30「建议收藏」在运行的时候出现这个错误,版本的要求不一样点上对勾,直接apply就可以了

  • 数据同步工具

    数据同步工具公司要搞数据平台,首当其冲的是把旧库的数据导入到新库中,原本各种数据库大部分都提供了导入导出的工具,但是数据存储到各个地方,mongdb,hbase,mysql,oracle等各种各样的不同数据库,同步起来头都大了因此最近使用了一些数据同步工具,记录下来:离线导入导出DataX阿里的Datax是比较优秀的产品,基于python,提供各种数据村塾的读写插件,多线程执行,使用起…

  • mapminmax函数

    mapminmax函数几个要说明的函数接口:[Y,PS]=mapminmax(X)[Y,PS]=mapminmax(X,FP)Y=mapminmax(‘apply’,X,PS)X=mapminmax(‘reverse’,Y,PS)用实例来讲解,测试数据x1=[124],x2=[523];[y,ps]=mapminmax(x1)y=-1.0000-0.3…

  • dom 自定义事件_pix4D生成dom

    dom 自定义事件_pix4D生成dom之前做项目都是直接用jquery的bind绑定事件,不过当时都不是动态生成dom元素,而是已经页面中原本存在的dom元素进行事件绑定,最近在测试给动态生成的dom绑定事件的时候发现事件失效,于是就测试了一下:1.事件失效的原因:(1)bind事件绑定只对dom中存在的元素有效,对于我们后来动态增加的元素是监测不到,所以绑定不了(2)同样,当你使用varaa=docu

  • 黑客入门视频教程(共57个)全实战过程

    黑客入门视频教程(共57个)全实战过程黑客入门视频教程(共57个)全实战过程 01ping命令的使用http://images.enet.com.cn/eschool/wmv/ping.wmv02netstat命令的使用http://images.enet.com.cn/eschool/wmv/netstat.wmv03tasklist和taskkill的使用h…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号