안드로이드 스튜디오/텍스트뷰(TextView)
[Android] 안드로이드 TextSwitcher 알아보기
민트왕자
2022. 9. 12. 11:12

1. TextSwitcher 개요
TextSwitcher는 TextView에 애니메이션을 입혀 사용자들로 하여금 마치 PPT를 보는 듯한 시각적 효과를 구현하는 도구입니다.
2. TextSwitcher 구현하기(XML)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextSwitcher
android:id="@+id/tsw"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inAnimation="@anim/alpha_start"
android:outAnimation="@anim/alpha_end"/>
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="다음"
android:textSize="18dp"/>
</LinearLayout>
간단하게 TextSwitcher, Button을 넣어줬습니다.
TextSwitcher 속성 중 inAnimation과 outAnimation을 활용해 시작 애니메이션, 종료 애니메이션을 구현합니다.
alpha_start
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:duration="1000"
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator" />
</set>
alpha_end
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:duration="1000"
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator" />
</set>
3. TextSwitcher 구현하기(JAVA)
public class MainActivity extends Activity
{
TextSwitcher tsw;
String[] str = {"딸기", "사과", "배", "키위", "바나나"};
int num;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tsw = findViewById(R.id.tsw);
Button btn = findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View p1)
{
if(num < str.length-1) {
num++;
} else {
num=0;
}
tsw.setText(str[num]);
}
});
tsw.setFactory(new ViewSwitcher.ViewFactory(){
@Override
public View makeView()
{
TextView txt = new TextView(MainActivity.this);
txt.setGravity(Gravity.CENTER);
txt.setTextSize(20);
return txt;
}
});
tsw.setCurrentText(str[0]);
}
}
TextSwitcher는 자식으로 TextView를 바꿔가며 애니메이션을 주는 도구입니다. 편리성을 위해 ViewFactory 기능을 통해 TextView를 자동으로 바꿔줄 수 있도록 합니다.
초기 텍스트는 setCurrentText 속성을 이용해 구현해줍니다. 첫화면에는 애니메이션 효과가 적용되지 않습니다.
버튼을 누를 때마다 문자열의 다음 텍스트로 전환되도록 구현하였습니다.
4. 실제 구현 결과

개발자 문서:
TextSwitcher
https://developer.android.com/reference/android/widget/TextSwitcher