Table of contentsAt some point you will want to go beyond the views provided by Android and write your own. In this guide, we will write a trivial custom view, and reference it in an XML layout. Create Custom ViewTo create a custom view, use Project -> Add New Item. Choose the "View" template and name it DemoView.cs. We'll modify the default template to paint the canvas blue so we can tell if it's working: namespace DemoViewApplication
{
public class DemoView : View
{
public DemoView (Context context, IAttributeSet attrs) : base (context, attrs)
{
}
public DemoView (Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle)
{
}
protected override void OnDraw (Android.Graphics.Canvas canvas)
{
base.OnDraw (canvas);
canvas.DrawColor (Color.Blue);
}
}
}
Reference View in LayoutNow modify your layout file to reference your view: <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<demoviewapplication.DemoView
android:id="@+id/demoview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Note: The tricky part is correctly referencing your view. To fit Java requirements, namespaces are lower-cased, and layout files reference the Java representation of your view. Thus, you must take the fully qualified name of your class "DemoViewApplication.DemoView" and lower-case the namespace portion: "demoviewapplication.DemoView". If you do not, you will receive a logcat error like this:
Running the CodeRunning the code should produce the following:
|