Use TextSwitcher with animation

Description

The following code shows how to Use TextSwitcher with animation.

Example


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextSwitcher
        android:id="@+id/your_textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:onClick="onSwitchText"
        android:text="Click me" />

</RelativeLayout>

Java code


import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;
/*from w w w  .  j  a v  a  2  s .  c  o m*/
public class MainActivity extends Activity {

  private static final String[] TEXTS = { "First", "Second", "Third" };
  private int mTextsPosition = 0;
  private TextSwitcher mTextSwitcher;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mTextSwitcher = (TextSwitcher) findViewById(R.id.your_textview);

    mTextSwitcher.setFactory(new ViewFactory() {
      @Override
      public View makeView() {
        TextView t = new TextView(MainActivity.this);
        t.setGravity(Gravity.CENTER);
        return t;
      }
    });

    mTextSwitcher.setInAnimation(this, android.R.anim.fade_in);
    mTextSwitcher.setOutAnimation(this, android.R.anim.fade_out);

    onSwitchText(null);
  }

  public void onSwitchText(View v) {
    mTextSwitcher.setText(TEXTS[mTextsPosition]);
    setNextPosition();
  }

  private void setNextPosition() {
    mTextsPosition = (mTextsPosition + 1) % TEXTS.length;
  }
}
Use TextSwitcher with animation




















Home »
  Android »
    Android UI »




UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView