Android TextWatcher监控EditText中的输入内容并限制其个数
程序员文章站
2022-08-02 16:57:18
布局中edittext在android布局中经常用到,对edittext中输入的内容也经常需要进行限制,我们可以通过textwatcher去观察输入框中输入的内容,作个笔记...
布局中edittext在android布局中经常用到,对edittext中输入的内容也经常需要进行限制,我们可以通过textwatcher去观察输入框中输入的内容,作个笔记。
主布局:
<?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; /** called when the activity is first created. */ @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); } } }; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 自制雪糕健康诱人,你还不会做?