안드로이드 TextSwitcher 사용하기
TextSwitcher 는 Text를 변경하는데 사용하는 View입니다.
Text를 변경할 때 효과를 줄 수 있다는 장점이 있습니다.
다음 예제는 Apidemos에 나온 것과 동일한 내용을 다룹니다.
다른 점은 ApiDemos는 버튼에 반응하지만, 이 예제는 TextSwitcher를 한번 클릭할 때 반응합니다.
1. 기본 프로젝트를 생성합니다.
2. main.xml의 내용을 아래와 같이 수정합니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextSwitcher android:id="@+id/time_switcher"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_gravity="center_horizontal"/>
</LinearLayout>
3. 소스 파일을 열고 아래와 같이 코딩합니다.
package com.sohon.app.dynamicWP;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;
public class ActContent extends Activity implements ViewFactory {
private TextSwitcher timeSwitcher;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timeSwitcher = (TextSwitcher) findViewById(R.id.time_switcher);
timeSwitcher.setFactory(this);
timeSwitcher.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ActContent.this.nextText();
}
});
Animation in = AnimationUtils.loadAnimation(this,
android.R.anim.fade_in);
Animation out = AnimationUtils.loadAnimation(this,
android.R.anim.fade_out);
timeSwitcher.setInAnimation(in);
timeSwitcher.setOutAnimation(out);
timeSwitcher.setText("1초");
}
protected void nextText() {
timeSwitcher.setText("2초");
}
public View makeView() {
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(36);
return t;
}
}
timeSwitcher.setFactory(this); 라는 문장은 매우 중요합니다.
이게 없으면 java.lang.NullPointerException 가 발생합니다.
setFactory를 추가하면 ViewFactory를 구현할 것을 요구합니다.
여기에 추가하는 View를 이용해 TextView를 생성하는 것 같습니다.