Xamarin - Documentation

Android

change platform

  1. Xamarin
  2. Android
  3. Advanced Topics
  4. Using Custom Views in a Layout

Using Custom Views in a Layout

At 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 View

To 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 Layout

Now 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:

android.view.InflateException: Binary XML file line #7: Error inflating class DemoViewApplication.DemoView

Running the Code

Running the code should produce the following:

CustomViewLayout1.png