Friday 27 January 2012

Android: getting text to roll (marquee animate) in TextView

Set the following TextView properties in your xml layout file…

<TextView
 …
 android:id="@+id/myTextView"
 android:singleLine="true"
 android:ellipsize="marquee"
 android:marqueeRepeatLimit="marquee_forever"
 android:focusable="true"
 android:focusableInTouchMode="true"
 … />

… and now whenever the width of the text in the TextView is longer than the width of the TextView itself, the text will roll right to left along the TextView repeatedly. The number of times the animation repeats is determined by the integer value you set marqueeRepeatLimit to.

Note that sometimes the above is not sufficient and you need to make the following call in your code:
myTextView.setSelected(true);

Done!

Thursday 26 January 2012

Android: using ViewSwitcher with in and out animations

In your xml layout file, you'll want something like the followng…

<ViewSwitcher
 android:id="@+id/viewSwitcher"
 android:inAnimation="@android:anim/slide_in_left"
 android:outAnimation="@android:anim/slide_out_right"
 … >
<View
 android:id="@+id/myFirstView"
 … />
<View
 android:id="@+id/mySecondView"
 … />

… This defines a ViewSwitcher which slides the next View to be shown in from the left and slides the current View out to the right.

In your code then where this layout file is referenced, you can initialise your Views as follows...

ViewSwitcher viewSwitcher =
 (ViewSwitcher)findViewById(R.id.viewSwitcher);
View myFirstView = findViewById(R.id.myFirstView);
View mySecondView = findViewById(R.id.mySecondView);

… And define some helper methods like the following to toggle between the two Views…

void showFirstView()
{
 if (viewSwitcher.getCurrentView() != myFirstView)
  viewSwitcher.showPrevious();
}

void showSecondView()
{
 if (viewSwitcher.getCurrentView() != mySecondView)
  viewSwitcher.showNext();
}

Done! And I guess the above applies equal well for ViewFlipper too.

Other animations are available too like fading in and fading out. Check out the following reference:
http://developer.android.com/reference/android/R.anim.html