Monday, July 8, 2013

CUSTOM VIEWS WITH MONODROID

There are 2 ways to create custom views/controls with Android. You can either extend the View class (or other classes inheriting from it), or you can extend a Layout class. What I’ve found (for now) to be the simplest path to the goal is the latter. Here’s how.
Let’s say I want to create a custom control called PersonControl.

public class PersonControl : LinearLayout, IPersonView
{
private Activity m_context;
public PersonControl(Context context)
: base(context)
{
Init(context);
}
public PersonControl(Context context, IAttributeSet attrs)
: base(context, attrs)
{
Init(context);
}
private void Init(Context context)
{
m_context = (Activity)context;
Inflate(context, Resource.Layout.PersonControl, this);
}
public byte[] Image
{
set
{
m_context.RunOnUiThread(() =>
{
var bm = BitmapFactory.DecodeByteArray(value, 0, value.Length);
var imgView = FindViewById<ImageView>(Resource.Id.thumbnailImage);
imgView.SetScaleType(ImageView.ScaleType.FitCenter);
imgView.SetPadding(8, 8, 8, 8);
imgView.SetImageBitmap(bm);
});
}
}
public string LastName
{
set
{
var textView = FindViewById<TextView>(Resource.Id.lastName);
textView.Text = value;
}
}
public string FirstName
{
set
{
var textView = FindViewById<TextView>(Resource.Id.firstName);
textView.Text ="@"+ value;
}
}
public int Age
{
set
{
var textView = FindViewById<TextView>(Resource.Id.age);
textView.Text = string.Format(textView.Text,value);
}
}
}
Here’s the associated xml layout.
12345678910111213141516171819202122232425262728293031323334353637
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:paddingRight="2px"
android:paddingLeft="2px"
android:paddingBottom="2px"
android:paddingTop="2px">
<TextView
android:text="{0} years old"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/age"
android:textStyle="italic"
android:typeface="serif" />
<ImageView
android:src="@android:drawable/ic_menu_gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:id="@+id/thumbnailImage" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/lastName"
android:textColor="@android:color/background_dark"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/buttonBarButtonStyle"
android:id="@+id/firstName"
android:typeface="serif" />
</LinearLayout>

No comments:

Post a Comment