擴(kuò)展TextField,合理計(jì)算中文字符長(zhǎng)度
Posted on 2009-07-03 14:47 AntiquMan 閱讀(518) 評(píng)論(0) 編輯 收藏 所屬分類(lèi): FlexCode
調(diào)用方法和普通TextField無(wú)異
一般的輸入,粘貼等操作均沒(méi)問(wèn)題..
直接對(duì)text進(jìn)行賦值沒(méi)有進(jìn)行限制 (原來(lái)的TextField也沒(méi)限制)..
如需限制~可以調(diào)用一次maxChars = maxChars即可..
01.
//Copyright © 2009. Http://L4cd.Net All Rights Reserved.
02.
package
net.L4cd.display
03.
{
04.
import
flash.events.Event;
05.
import
flash.events.TextEvent;
06.
import
flash.text.TextField;
07.
import
flash.utils.ByteArray;
08.
09.
/**
10.
* 擴(kuò)展TextField類(lèi),中文以2字符長(zhǎng)度計(jì)算
11.
*
12.
* @author L4cd.Net
13.
* @playerversion Flash player 9
14.
* @langversion 3.0
15.
* @version 2009-06-16
16.
*/
17.
public
class
TextFieldExt
extends
TextField
18.
{
19.
private
var
_maxChars:
int
= -
1
;
20.
public
function
TextFieldExt()
21.
{
22.
super
();
23.
24.
}
25.
override
public
function
get
maxChars():
int
26.
{
27.
return
_maxChars;
28.
}
29.
override
public
function
set
maxChars(value:
int
):
void
30.
{
31.
_maxChars = value;
32.
if
(maxChars<
0
)
33.
{
34.
removeEventListener(TextEvent.TEXT_INPUT,input);
35.
}
else
36.
{
37.
addEventListener(TextEvent.TEXT_INPUT,input);
38.
text = getTextByCharLength(text,maxChars);
39.
}
40.
}
41.
override
public
function
get
length():
int
42.
{
43.
return
getCharLength(text);
44.
}
45.
private
function
input(e:TextEvent):
void
46.
{
47.
//攔截并阻止textinput事件,手動(dòng)處理內(nèi)容輸入
48.
var
textField:TextField = e.currentTarget
as
TextField;
49.
var
temp:
String
= getTextByCharLength(e.text,maxChars - getCharLength(text) + getCharLength(selectedText));
50.
var
index:
int
= selectionBeginIndex;
51.
replaceText(selectionBeginIndex,selectionEndIndex,temp);
52.
setSelection(index+temp.length,index+temp.length);
53.
dispatchEvent(
new
Event(Event.CHANGE,
true
));
54.
e.preventDefault();
55.
}
56.
/**
57.
* 獲取字符長(zhǎng)度,一個(gè)中文算2長(zhǎng)度
58.
* @param txt
59.
* @return 返回長(zhǎng)度值
60.
*/
61.
private
function
getCharLength(txt:
String
):
int
62.
{
63.
var
byte:ByteArray =
new
ByteArray();
64.
byte.writeMultiByte(txt,
"gb2312"
);
65.
byte.position =
0
;
66.
return
byte.bytesAvailable;
67.
}
68.
/**
69.
* 截取指定長(zhǎng)度的文本內(nèi)容,一個(gè)中文算2長(zhǎng)度
70.
* @param txt 需要截取的文本
71.
* @param length 需要截取的長(zhǎng)度
72.
* @return 截取后的內(nèi)容
73.
*/
74.
private
function
getTextByCharLength(txt:
String
,length:
int
):
String
75.
{
76.
if
(length<
1
)
return
""
;
77.
var
byte:ByteArray =
new
ByteArray();
78.
byte.writeMultiByte(txt,
"gb2312"
);
79.
byte.position =
0
;
80.
return
byte.readMultiByte(Math.min(length,byte.bytesAvailable),
"gb2312"
);
81.
}
82.
}
83.
}
調(diào)用方法和普通TextField無(wú)異
1.
import
net.L4cd.display.TextFieldExt
2.
var
ext:TextFieldExt =
new
TextFieldExt();
3.
ext.maxChars =
15
;
4.
addChild(ext);
一般的輸入,粘貼等操作均沒(méi)問(wèn)題..
直接對(duì)text進(jìn)行賦值沒(méi)有進(jìn)行限制 (原來(lái)的TextField也沒(méi)限制)..
如需限制~可以調(diào)用一次maxChars = maxChars即可..