Archive for the ‘Uncategorized’ Category

Mono Android: Marquee Text View

Friday, November 11th, 2011

On mobile devices you have a limited set of real estate on the screen, often the text you need to display is to long to be shown.  You have several options, you can wrap it and take up additional vertical space, you ellipse it and expand it in a dialog, or you can scroll it marquee style to display it. Android supports all of these options, the one I chose to use for certain situations is marquee because its unobtrusive and can easily display the data to the user with zero interaction on their part.

There are some issues with the control unfortunately, one of them being the default behavior is to not marquee the text unless the TextView has focus.  The fix to this in Android is easy, inherit from TextView and override a couple of methods.  In Mono Android it was not so clear, I fussed with this for a while before diving into reflection to actually figure out how to get this to work.

Here is the code to allow a Marquee TextView in Mono Android:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class MarqueeTextView : TextView
{
[Register(".ctor", "(Landroid/content/Context;)V", "")]
public MarqueeTextView(Context context)
: base(context) { }
public MarqueeTextView(IntPtr doNotUse)
: base(doNotUse) { }
[Register(".ctor", "(Landroid/content/Context;Landroid/util/AttributeSet;)V", "")]
public MarqueeTextView(Context context, IAttributeSet attrs)
: base(context, attrs) { }
[Register(".ctor", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V", "")]
public MarqueeTextView(Context context, IAttributeSet attrs, int defStyle)
: base(context, attrs, defStyle) { }
protected override void OnFocusChanged(bool gainFocus, FocusSearchDirection direction, Android.Graphics.Rect previouslyFocusedRect)
{
if (gainFocus)
base.OnFocusChanged(gainFocus, direction, previouslyFocusedRect);
}
public override void OnWindowFocusChanged(bool hasWindowFocus)
{
if (hasWindowFocus)
base.OnWindowFocusChanged(hasWindowFocus);
}
public override bool IsFocused
{
get
{
return true;
}
}
}