Overriding TextView – MBTA Trip Tracker

In my previous post I designed for the data collection screen for the my MBTA Trip Tracker, one that mimics the layout of the paper tickets handed out by conductors.

There didn’t appear to be an android: attribute to put a border around Android’s TextView control (the equivalent of a .NET Label). A quick Google search turned up a post on Stack Overflow which suggested creating a new class that inherited from TextView and override its OnDraw method to create the border.

</p>

<dl>
<dt>public class BorderedTextView : TextView</dt>
<dt>{</dt>
<dt>public BorderedTextView(Context context, IAttributeSet attrs, int defStyle)</dt>
<dd>base(context, attrs, defStyle){}</dd>

<dt>public BorderedTextView(Context context, IAttributeSet attrs)</dt>
<dd>base(context, attrs){}</dd>

<dt>public BorderedTextView(Context context)</dt>
<dd>base(context){}</dd>
</dl>

<p>protected override void OnDraw(Android.Graphics.Canvas canvas)
{
base.OnDraw(canvas);</p>

<p>Rect rect = new Rect();
Paint paint = new Paint();</p>

<p>paint.SetStyle(Android.Graphics.Paint.Style.Stroke);
paint.Color = Android.Graphics.Color.White;
paint.StrokeWidth = 3;</p>

<p>GetLocalVisibleRect(rect);
canvas.DrawRect(rect, paint);
}</p>

<p>}</p>

<p>

Combined with an XML layout and some help from these two web pages – Using Custom Views in a Layout and Declaring a Custom Android UI Element using XML.

</p>

<p><?xml version="1.0" encoding="utf-8"?>
&lt;LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/mbta"</p>

<p>android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"></p>

<p>&lt;mbta.BorderedTextView android:id="@+id/setcurrentdate"
android:text="Set Current Date"
android:textSize="15pt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal|center_vertical"
android:layout_weight="1"/></p>

<p>&lt;mbta.BorderedTextView android:id="@+id/selectstarttime"
android:text="Select Start Time"
android:textSize="15pt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal|center_vertical"
android:layout_weight="1"/></p>

<p></LinearLayout></p>

<p>

Gave me the user interface I wanted.

Another hour or two of fiddling with Android layout XML and some reading about Supporting Multiple Screens gave me a final layout embedded in a ScrollView that appears the same on multiple screen sizes and densities.

  

Next, event handling for TextView touches.

This entry was posted in Side Projects, Software Development and tagged , , . Bookmark the permalink.