EditText限制輸入字串長度

2021-07-09 05:54:00 字數 1988 閱讀 5629

edittext限制字串輸入長度的改動辦法:

1、在 xml 檔案中設定文字編輯框屬性作字元數限制

如:android:maxlength="10" 即限制最大輸入字元個數為10

2、在**中使用inputfilter 進行過濾

inputfilter); 即限定最大輸入字元數為20

也可在inputfilter裡新增新方法

public static class adnnamelengthfilter implements inputfilter

else

int keep = nmax - (dest.length() - (dend - dstart));

if (keep <= 0) else if (keep >= end - start) else

}return source.subsequence(start, start + keep);}}

}

根據輸入字串或者顯示字串的位元組長度和字串長度判斷,因為漢字在android中乙個字元佔3個位元組,edittext輸入最長為32個位元組所以漢字只能輸入10個字元。

3、利用 textwatcher 進行監聽

package com.example.test12;

import android.os.bundle;

import android.r.menu;

import android.text.editable;

import android.text.textwatcher;

import android.util.log;

import android.view.menu;

import android.widget.edittext;

public class mainactivity extends activity implements textwatcher

@override

public boolean oncreateoptionsmenu(menu menu)

@override

public void aftertextchanged(editable s)

@override

public void beforetextchanged(charsequence s, int start, int count,

int after)

log.d("txx","beforetextchanged-s:"+s);

log.d("txx","beforetextchanged-start:"+start);

log.d("txx","beforetextchanged-count:"+count);

log.d("txx","beforetextchanged-after:"+after);

}@override

public void ontextchanged(charsequence s, int start, int before, int count)

}if(inputbytelength > max_byte_length)

}}

輸入的字串限制最大為30個位元組,遍歷輸入的字串字元得出位元組長度如果大於max_byte_length最大位元組數,則返回從0到i的字串。

在對應的activity中呼叫textwather

package cie.textedit; 

import android.os.bundle;

import android.text.inputfilter;

import android.widget.edittext;

publicclass texteditactivity extends activity

}

EditText 限制可輸入的字元

今天在專案中遇到了edittext設定登入密碼的時候,輸入了中文字元,這樣一來就和pc端相衝突了.想了很久,嘗試了幾個辦法,仍然沒有有效的解決.1.通過matcher來過濾掉其中的中文字元 判斷是否有中文字元 static string regex u4e00 u9fa5 static patter...

EditText限制文字輸入

private final textwatcher mtextwatcher new textwatcher public void ontextchanged charsequence s,int start,int before,int count public void aftertextch...

EditText限制輸入字元長度和回車

實際情況下客戶輸入edittext多個回車或很多字元會造成顯示問題 有時擷取字元也挺麻煩,所以總結了下 注 回車預設情況按乙個字元處理 設定maxline maxlength並限制不了多個回車 限制edittext輸入回車 edtschedulename.setoneditoractionliste...