【AndroidのViewを制する】 TextSwitcherを使いこなしてTextViewを切り替える
今回、紹介するTextSwitcherはViewSwitcherを継承しています。
ViewSwitcherとの違いはTextViewを切り替えることに特化していることです。
TextView以外を設定すると例外で強制終了します。
TextSwitcher#setTextを使って次のTextViewを表示する
TextSwitcher#setTextは次のTextViewに文字列を設定し表示するメソッドです。この時インアニメーションとアウトアニメーションが実行されます。
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
// TextSwitcherをインスタンス化
final TextSwitcher textSwitcher = new TextSwitcher(this);
// TextSwitcherにTextViewを設定する。
textSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
return new TextView(TextSwitcherActivity.this);
}
});
// インアニメーションを設定する。
AlphaAnimation inAnimation = new AlphaAnimation(0,1);
inAnimation.setDuration(500);
inAnimation.setStartOffset(500);
textSwitcher.setInAnimation(inAnimation);
// アウトアニメーションを設定する。
AlphaAnimation outAnimation = new AlphaAnimation(1,0);
outAnimation.setDuration(500);
textSwitcher.setOutAnimation(outAnimation);
// TextSwitcher.setTextを使って次のViewを表示する。
Button setTextButton = new Button(this);
setTextButton.setText("現在時刻");
setTextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textSwitcher.setText(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()));
}
});
linearLayout.addView(textSwitcher);
linearLayout.addView(setTextButton);
setContentView(linearLayout);
TextSwitcher#setCurrentTextを使って、現在のTextViewを変更する
TextSwitcher#setCurrentTextは現在のTextViewに文字列を設定するメソッドです。このメソッドでは文字列を変更するだけなのでインアニメーションとアウトアニメーションは実行されません。
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
// TextSwitcherをインスタンス化
final TextSwitcher textSwitcher = new TextSwitcher(this);
// TextSwitcherにTextViewを設定する。
textSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
return new TextView(TextSwitcherActivity.this);
}
});
// インアニメーションを設定する。
AlphaAnimation inAnimation = new AlphaAnimation(0,1);
inAnimation.setDuration(500);
inAnimation.setStartOffset(500);
textSwitcher.setInAnimation(inAnimation);
// アウトアニメーションを設定する。
AlphaAnimation outAnimation = new AlphaAnimation(1,0);
outAnimation.setDuration(500);
textSwitcher.setOutAnimation(outAnimation);
// TextSwitcher.setCurrentTextを使って現在のテキストを変更する。
Button setCurrentTextButton = new Button(this);
setCurrentTextButton.setText("初期化");
setCurrentTextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textSwitcher.setCurrentText("初期化");
}
});
linearLayout.addView(textSwitcher);
linearLayout.addView(setCurrentTextButton);
setContentView(linearLayout);