Flex クリックやフォーカスイン時にTextInputのテキストを選択状態にするサンプル
Flex クリックやフォーカスイン時にTextInputのテキストを選択状態にするサンプルです。
Flex(AIR) にてテキストボックスを配置する場合、TextInput
コントロールを利用します。
今回は「クリックされた時やフォーカスインした際に、入力された値を選択状態にする方法」をご紹介したいと思います。
Sponsored Links
目次
完成図
完成図はこんな感じです。
Sponsored Links
サンプルソース
それでは、実際のソースを見ながら解説してきます。
CharacterTextInput.as
TextInput
クラスを継承した CharacterTextInput
を用意しました。
package { import flash.events.Event; import flash.events.FocusEvent; import flash.events.MouseEvent; import mx.controls.TextInput; /** * TextInput for Character input. */ public class CharacterTextInput extends TextInput { // テキストを選択状態に設定 private var firstClickFlg:Boolean = true; /** * コンストラクタ */ public function CharacterTextInput() { super(); this.addEventListener(MouseEvent.CLICK, function(event:Event):void { if ( event.currentTarget.text != "" && event.currentTarget.text != undefined ) { // 初回のみ選択状態を作る if ( this.firstClickFlg ) event.currentTarget.setSelection(0, event.currentTarget.length); this.firstClickFlg = false; } }); } /** * @private * Gets called by internal field so we draw a focus rect around us. */ override protected function focusInHandler(event:FocusEvent):void { super.focusInHandler(event); // テキストを選択状態に設定 if ( event.currentTarget.text != "" && event.currentTarget.text != undefined ) event.currentTarget.setSelection(0, event.currentTarget.length); this.firstClickFlg = false; } /** * @private * Gets called by internal field so we remove focus rect. */ override protected function focusOutHandler(event:FocusEvent):void { super.focusOutHandler(event); this.firstClickFlg = true; } } }
コンストラクタ
マウスでクリックされたときに、setSelection を使って、テキストを選択状態にしています。ただし、選択状態を解除できないと、これはこれで入力しにくいので、一度だけ選択状態を作り、その後解除しています。
フォーカスインイベントハンドラ(focusInHandler)
ここでも、setSelection を使って、テキストを選択状態にしています。
フォーカスアウトイベントハンドラ(focusOutHandler)
ここでは、再度クリックされた時を考慮し、一度だけ選択状態を作るフラグを戻しています。
CharacterTextInputTest.mxml
表示する画面は以下の通りです。画面デザインを整えるために、css
を用意しています。
<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:local="*" initialize="onInit()" width="600" height="40" > <fx:Script> <![CDATA[ /** * 初期化 */ protected function onInit():void { StyleManager.getStyleManager(null).loadStyleDeclarations("css/blue.swf"); } ]]> </fx:Script> <fx:Declarations> </fx:Declarations> <mx:VBox width="100%"> <mx:FormItem width="100%" label="文字列入力"> <s:HGroup width="100%" gap="0"> <local:CharacterTextInput id="stringText" text="選択状態" width="100" imeMode="JAPANESE_HIRAGANA" /> <mx:Text text="クリックすると一度だけテキストが選択状態になります。"/> </s:HGroup> </mx:FormItem> </mx:VBox> </s:Application>
サンプルソースのダウンロード
サンプルソースは こちら からダウンロードできます。
おつかれさまでした。
Sponsored Links