Jun 8, 2012

Creating a MarqueeLayout with the Android Animation System

When I posted the article about the hidden BlinkLayout inside Android’s LayoutInflater Thierry-Dimitri Roy wrote on Google+:



That’s a challenge I accept! Back in the days when I worked at Jimdo we developed “a lifeboat for GeoCities” which allowed users to migrate their GeoCities website to Jimdo before GeoCities finally shut down in 2009. So I’ve some kind of heart for GeoCities users.

The view animation system of Android makes it quite easy to develop something like a MarqueeLayout. All we need to do is to extend an existing ViewGroup and attach a marquee-like animation to every instance.

The TranslateAnimation does already exactly what we need: It moves a view from a starting position to an ending position. The two positions can either be declared absolute (position on the screen) or relative to the view or its parent. After that we only need to define the duration of the animation and Android will do the rest for us.

We'll define the start and end positions of the animation by using coordinates relative to the view. When using relative coordinates you can think of our view having a size of 1x1 and it's top left corner placed at (0,0).

View of size 1x1 at position (0,0)

If our view's width stretches to the whole width of the screen we can consider the screen's size also 1 (relative to the view's width).

View (green) filling full width of screen (grey)

Assuming a screen size of 1 and a starting position on the right side outside of the screen gives us a relative starting position of (1,0). This will place our view exactly outside the screen (or it's parent).

View animation starting at (1,0)

The view should move from the starting position to the left until it's outside of the screen at (-1, 0).

View animation stopping at (-1,0)

The animation system will generate all transient positions needed for the animation. Given all the information above we can write a simple MarqueeLayout in a few lines:

MarqueeLayout.java

That's what our MarqueeLayout looks like when adding a TextView to it:


The following code was used to set up an activity using our MarqueeLayout:

MarqueeLayoutActivity.java

1 comment:

  1. Elison J. G. LusvardiNovember 8, 2012 at 1:37 PM

    Hi! How are you?
    I was trying make something similar based in your idea, but I've got a problem... when my text in textView is bigger than screen, the text is appended and dont was showed properly... do you know if the textView can animate only the text, or wrap all the text?

    I've tryed set the values in code:
    TextView temp = new TextView(context);
    temp.setText(item);
    temp.setSingleLine(true);
    temp.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    temp.setTextColor(Color.WHITE);

    but do not work... =[

    thanks!

    ReplyDelete