Просмотр полной версии : расширение TextInput
Привет!
Есть задача расширить TextInput для того, чтобы контролировать ввод символов и подставлять в зависимости от нажатой клавиши свои символы.
Никак не пойму, какое событие TextInput отвечает за ввод символов.
Подсажите, пжта.
Не смотрел, но в AS2 был onChanged для TextField…
vooparker
09.06.2007, 01:00
Я как-то расширял TextArea, чтобы ловился разрыв строки и на новую подставлялись пробельные символы отступа предыдущей строки. Если интересно могу выложить код.
vooparker
09.06.2007, 10:05
Собственно, TextAreaExtended в моем исполнении =)
package com.yarovoy.vooparker.controls
{
import mx.controls.TextArea;
import flash.ui.Keyboard;
import flash.events.TextEvent;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
/**
* TextAreaExtended. Class gives extended possibility
* to TextArea control such as allowing TabKey,
* keepint indent white-spaces in the beginnig of new line.
* @author Alexey "Vooparker" Anickutin
*/
public class TextAreaExtended extends TextArea
{
// -------------------------------------------------------
// Props
// -------------------------------------------------------
/**
* @private
*/
private var _allowTabKey : Boolean;
/**
* @private
*/
private var _whiteSpaces : Boolean;
// -------------------------------------------------------
// Getters & Setters
// -------------------------------------------------------
/**
* Allow Tab Key
*
* @default false
*/
public function get allowTabKey ( ) : Boolean
{
return _allowTabKey;
}
/**
* @private
*/
[Bindable]
public function set allowTabKey ( value : Boolean ) : void
{
if ( value )
{
addEventListener( FocusEvent.KEY_FOCUS_CHANGE, tabKeyHandler );
}
else
{
removeEventListener( FocusEvent.KEY_FOCUS_CHANGE, tabKeyHandler );
}
_allowTabKey = value;
}
/**
* Keep indent white-spaces in the beginnig of new line.
*
* @default false
*/
public function get whiteSpaces ( ) : Boolean
{
return _whiteSpaces;
}
/**
* @private
*/
[Bindable]
public function set whiteSpaces ( value : Boolean ) : void
{
if( value )
{
addEventListener( KeyboardEvent.KEY_DOWN, addWhiteSpaces );
}
else
{
removeEventListener( KeyboardEvent.KEY_DOWN, addWhiteSpaces );
}
_whiteSpaces = value;
}
// -------------------------------------------------------
// Constructor
// -------------------------------------------------------
/**
* Constructor
*/
public function TextAreaExtended ( )
{
super( );
init( );
}
// -------------------------------------------------------
// Private methods.
// -------------------------------------------------------
/**
* Init TextAreaExtended control
*
* @private
*/
private function init ( ) : void
{
allowTabKey = false;
whiteSpaces = false;
}
/**
* Catch Tab key.
*
* @private
*/
private function tabKeyHandler ( e : FocusEvent = null ) : void
{
if ( e != null )
{
insert( "\t" );
e.preventDefault( );
setFocus( );
dispatchEvent( new TextEvent( TextEvent.TEXT_INPUT ) );
}
}
/**
* Add indent white-spaces in the beginnig of new line.
*
* @private
*/
private function addWhiteSpaces ( e : KeyboardEvent = null ) : void
{
if( e !== null && e.keyCode == Keyboard.ENTER )
{
var wsp : RegExp = /^([\t ]*)/;
var before : String = text.substring( 0, selectionBeginIndex );
var line : String = text.substring( before.lastIndexOf( "\r" ) + 1, selectionEndIndex );
var ws : Array = line.match( wsp );
var indent : String = ( ws ) ? ( ws[0] as String ) : "";
callLater( insert, new Array ( indent ) );
}
}
/**
* Insert some string in carret position
*
* @private
*/
private function insert ( str : String ) : void
{
var before : String = text.substring( 0, selectionBeginIndex );
var after : String = text.substring( selectionEndIndex, text.length );
text = before + str + after;
var newCarPos : int = selectionBeginIndex + str.toString( ).length;
setSelection( newCarPos, newCarPos );
}
// -------------------------------------------------------
// Public methods. API
// -------------------------------------------------------
}
}
PS. Почему то так и не смог прикрепить архив =(
2baron27: и посмотри пожалуйста личку =)
Powerhead
18.06.2007, 15:29
Обработка нажатий клавиш делается очень просто.
var myTxt:TextInput = new TextInput();
application.addChild(myTxt);
myTxt.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
private function keyHandler ( e:KeyboardEvent ) : void
{
if( e.keyCode == ....
}
необходмо не просто обработать, а переопределить значения клавиш.
Powerhead
18.06.2007, 17:46
Тогда лови Event.CHANGE и меняй текст или выполняй методы, в зависимости от нажатой нопки.
Вот пример. В текстинпуте "s" будет подменена на "G"
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="create();">
<mx:Script>
<![CDATA[
import mx.controls.TextInput;
public var txt:TextInput;
public var t:String = new String();
public var char:String = new String();
public function create():void {
txt = new TextInput();
application.addChild(txt);
txt.addEventListener(Event.CHANGE, changeHandler);
}
private function changeHandler(e:Event):void
{
t = e.currentTarget.text;
char = t.charAt(t.length - 1)
trace('Last char: '+char +' Code: '+char.charCodeAt(0));
if(char.charCodeAt(0) == 115) {
e.currentTarget.text = t.substr(0, t.length - 1) + 'G';
}
}
]]>
</mx:Script>
</mx:Application>
да, спасибо. Я пробовал этот способ. При нажатии двух клавиш одовременно не всегда удаляется нужный символ. Также если сделать рестрикт только английских буков и вставлять при русской раскладке вместо русских буков английские (типа Пунто свитчер), опять глюки.
Работает на vBulletin ® версия 3.7.3. Copyright ©2000-2026, Jelsoft Enterprises Ltd. Перевод: zCarot
Copyright © 1999-2008 Flasher.ru. All rights reserved.