第3弾。
javascriptでの実装はよく見かけますが、薄い文字であらかじめ入力例などを表示しておき、フォーカスされると、入力文字が消える入力フィールド(TextInput)のFlexでの実装例です。ちょっと長くなりますが・・・
ExampleTextInput
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | package hoge { import flash.events.Event; import flash.events.FocusEvent; import mx.controls.TextInput; import mx.events.FlexEvent; import mx.styles.CSSStyleDeclaration; import mx.styles.StyleManager; public class ExampleTextInput extends TextInput { private var thisStyle:CSSStyleDeclaration = new CSSStyleDeclaration("SampleTextInputCSS"); //ExampleText表示時のText Color private const EXAMPLE_TEXT_COLOR:int = 0x939393; //入力時のText Color private const NORMAL_TEXT_COLOR:int = 0x000000; //sampleText プロパティ [Inspectable(defaultValue="入力してください。")] private var __exampleText:String; public function get exampleText():String { return __exampleText; } public function set exampleText(str:String):void { this.__exampleText = str; } //data プロパティをオーバーライド public override function get data():Object { //sampleTextが表示されていたら空文字列を返す if (this.text == this.__exampleText ) { return ""; } else { return this.text; } } //コンストラクタ public function ExampleTextInput() { super(); this.addEventListener(FocusEvent.FOCUS_IN,onFocusIn); this.addEventListener(FocusEvent.FOCUS_OUT,onFocusOut); this.addEventListener(FlexEvent.INITIALIZE,onInit); } //初期化 private function onInit(event:Event):void { //sampleTextを表示させて文字をグレー表示する this.text = this.__exampleText; thisStyle.setStyle("color", this.EXAMPLE_TEXT_COLOR); StyleManager.setStyleDeclaration(this.className,thisStyle,true); } //Focus In private function onFocusIn(event:Event):void { //Textを空文字にして色を通常の色に設定する if (this.text == this.__exampleText) { this.text = ""; thisStyle.setStyle("color",this.NORMAL_TEXT_COLOR); StyleManager.setStyleDeclaration(this.className,thisStyle,true); } } //Focus Out private function onFocusOut(event:Event):void { //Textが空文字だったらExampleTextを設定してグレー表示にする if (this.text == "") { thisStyle.setStyle("color",this.EXAMPLE_TEXT_COLOR); StyleManager.setStyleDeclaration(this.className,thisStyle,true); this.text = this.__exampleText; } } } } |
このコントロールのインスタンスのtextプロパティをそのまま利用する場合、入力例が表示されている場合、入力例の文字列がtextプロパティで取得されてしまいます。それではちょっとまずいので、入力例が表示されている場合は、空文字列で返るのが望ましいですね。
したがって、data プロパティをオーバーライドし、dataプロパティを経由して値を取得することにします(31行目〜)。
MXML
<mx:Application
xmlns:mx=”http://www.adobe.com/2006/mxml”
xmlns:ns1=”hoge.*”
layout=”horizontal” height=”427″ width=”446″>:
:
<ns1:ExampleTextInput width=”60″ id=”comment” exampleText=”コメントを入力してください” />
<mx:Button click=”Alert.show(comment.data.toString)” />:
:
</mx:Application>
exampleText属性をExampleTextInputタグの中に記述すると、この文字列が入力例として表示されるようになります。
入力内容を参照する場合は、textプロパティではなく、dataプロパティを参照します。
この記事へのトラックバックURL:
2009/02/22 日 at 21:43:44
[…] … Flexで入力例を表示するTextInputを使用する 第3弾。 […]