ドキュメントには、テキスト フィールドに何かを書き込む前にテキストの形式を変更する場合は、新しい defaultTextFormat を割り当てると記載されています。それ以外の場合、新しい形式を設定すると、現在の選択が変更されます。
以下のソリューションは、テキスト フィールドにフォーカスを維持することで機能するため、ボタンをクリックしてもテキスト フィールドにフォーカスがあります。現在の選択がある場合、押されたボタンに応じて、選択が青または赤に変わります。選択がない場合は、新しいフォーマットが適用されたときにテキスト フィールドにまだフォーカスがあるため、以前の defaultTextFormats を変更せずに、新しい defaultTextFormat が適用されます。
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.events.MouseEvent;
import flash.events.FocusEvent;
public class ChangeTextColor extends Sprite
{
private var field:TextField;
private var redButton:Sprite;
private var blueButton:Sprite;
public function ChangeTextColor()
{
init();
}
//Initialize
private function init():void
{
//Create Text Field
field = new TextField();
field.type = TextFieldType.INPUT;
field.border = true;
field.x = field.y = 10;
addChild(field);
//Retain Focus On TextField
field.addEventListener(FocusEvent.FOCUS_OUT, fieldFocusOutHandler);
//Create Button
redButton = createButton(10, 120, 200, 20, 0xFF0000);
blueButton = createButton(10, 150, 200, 20, 0x0000FF);
}
//Create Button Method
private function createButton(x:uint, y:uint, width:uint, height:uint, color:uint):Sprite
{
var resultSprite:Sprite = new Sprite();
resultSprite.graphics.beginFill(color);
resultSprite.graphics.drawRect(0, 0, width, height);
resultSprite.graphics.endFill();
resultSprite.addEventListener(MouseEvent.CLICK, mouseClickEventHandler);
resultSprite.x = x;
resultSprite.y = y;
addChild(resultSprite);
return resultSprite;
}
//Apply Text Format
private function changeTextFormatColor(color:uint):void
{
var format:TextFormat = new TextFormat();
format.color = color;
//Change Format Of Selection Or Set Default Format
if (field.selectionBeginIndex != field.selectionEndIndex)
field.setTextFormat(format, field.selectionBeginIndex, field.selectionEndIndex);
else
field.defaultTextFormat = format;
}
//Maintain Focus Of TextField When Color buttons Are Clicked
private function fieldFocusOutHandler(evt:FocusEvent):void
{
stage.focus = evt.currentTarget as TextField;
}
//Button Click Event Handler
private function mouseClickEventHandler(evt:MouseEvent):void
{
switch (evt.currentTarget)
{
case redButton: trace("red clicked");
changeTextFormatColor(0xFF0000);
break;
case blueButton: trace("blue clicked");
changeTextFormatColor(0x0000FF);
}
}
}
}
または、テキスト フィールドに関連しない他のボタンがプログラムにあり、クリックするとテキスト フィールドのフォーカスが失われる場合は、fieldFocusOutHandler 関数を削除して、stage.focus = field; を配置します。buttonClickHandler メソッド内。これが問題になる場合は、fieldFocusOutHandler 関数を保持して調整することもできます。