[Xamarin.android] Custom controls

Source: Internet
Author: User

[Xamarin.android] Custom control preface

Software project development process, inevitably encountered some can not use the built-in control to meet customer needs, such as: Speed meter, line chart ... Wait a minute. At this point, developers can customize the control by customizing the control for the project to provide a more user-friendly interface. This article describes how to build a custom control when developing a xamarin.android project, leaving a record for yourself and hoping to help developers in need.

Building a custom control

In the Xamarin.android project, there are many ways to build custom controls, and the example in this article uses inherited view, overwrite OnDraw, to implement custom controls.

  1. First, in the Xamarin.android project, add a Category: "countmeter", and let Countmeter inherit Android. Views.view and the constructors corresponding to the Android.Views.View.

    public sealed class CountMeter : View{    // Constructors    public CountMeter(Context context) : base(context) { }    public CountMeter(Context context, IAttributeSet attributeSet) : base(context, attributeSet) { }    public CountMeter(Context context, IAttributeSet attributeSet, int defaultStyle) : base(context, attributeSet, defaultStyle) { }            // ......}
  2. Then, in the Countmeter category, overwrite the Onmeasure method of Android.Views.View, so that the custom control can correctly display Android:layoutwidth, android:layout Height ... And so on size setting.

    public sealed class CountMeter : View{    // Fields    private readonly int _defaultWidth = 400;    private readonly int _defaultHeight = 210;    // Methods    protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)    {        // Base        base.OnMeasure(widthMeasureSpec, heightMeasureSpec);        // Size        this.SetMeasuredDimension(this.MeasureSize(widthMeasureSpec, _defaultWidth), this.MeasureSize(heightMeasureSpec, _defaultHeight));    }    private int MeasureSize(int measureSpec, int defaultSize)    {        // Size        var specSize = MeasureSpec.GetSize(measureSpec);        // Measure        switch (MeasureSpec.GetMode(measureSpec))        {            case MeasureSpecMode.AtMost: return Math.Min(specSize, defaultSize);            case MeasureSpecMode.Exactly: return specSize;            default: return defaultSize;        }    }    // ......}

  3. Then in the Countmeter category, overwrite Android.Views.View's OnDraw method, using program code to describe how the custom control renders on the interface. For how to depict the appearance of a control, developers can refer to the following information to learn how to use the graphical depiction function through the drawing categories provided by Xamarin.android: "xamarin>android>other ux>drawing".

    public sealed class countmeter:view{//Fields private readonly int _defaultwidth = 400;    Private readonly int _defaultheight = 210; Methods protected override void OnDraw (canvas canvas) {//base base.        OnDraw (canvas); Background Canvas.        Drawcolor (Color.White);        Paint var paint = new paint (); Paint.        Color = color.red; Paint.        Strokewidth = 10;        Size var x = 0;        var y = 0; var width = this.        Width; var height = this.        Height-10;        var ellipsewidth = width;        var ellipseheight = height * 2;        var scalelength = 20;        var spacelength = 10; Scale paint.        Color = color.red; for (int scalecount = 0; scalecount <=; Scalecount + =) {var scaleangle = 180f/100f * Scalec            Ount;            var scaleoffset = scalelength; var scalePoint1 = this. Getellipsepoint (x, Y, Ellipsewidth, Ellipseheight, Scaleangle); var ScalePoint2 = this. Getellipsepoint (x + scaleoffset, y + scaleoffset, Ellipsewidth-scaleoffset * 2, Ellipseheight-scaleoffset * 2, ScaleAn            GLE); Canvas.        DrawLine (scalepoint1.x, Scalepoint1.y, scalepoint2.x, scalepoint2.y, paint); }    }    // ......}

  4. In addition to rendering static data, a custom control can be used to render dynamic data, for example: current speed, current temperature, cargo capacity ... Wait a minute. To complete the ability to render dynamic data, developers must include object properties, object methods in the custom control to provide external programs to enter Dynamic Data. In the control internal program, after updating the data, you can follow the data content to depict the corresponding display graphics on the screen.

    public sealed class countmeter:view{//Fields private int _count = 0;        Properties public int Count {get {//Get return _count;            } set {//Set _count = value; Refresh this.        Invalidate (); }}//Methods protected override void OnDraw (canvas canvas) {//base base.        OnDraw (canvas); Background Canvas.        Drawcolor (Color.White);        Paint var paint = new paint (); Paint.        Color = color.red; Paint.        Strokewidth = 10;        Size var x = 0;        var y = 0; var width = this.        Width; var height = this.        Height-10;        var ellipsewidth = width;        var ellipseheight = height * 2;        var scalelength = 20;        var spacelength = 10; Needle Paint.        Color = Color.gold;        var needleangle = 180f/100f * _COUNT; var needleoffset = scalelength + SPACElength; var needlePoint1 = this. Getellipsepoint (x + needleoffset, y + needleoffset, Ellipsewidth-needleoffset * 2, Ellipseheight-needleoffset * 2, nee        Dleangle);        var needlePoint2 = new PointF (WIDTH/2, height); Canvas.    DrawLine (needlepoint1.x, Needlepoint1.y, needlepoint2.x, needlepoint2.y, paint); }    // ......}

Using the custom control

After you have completed the development step of building a custom control, you will then add the custom control to the project. In the Xamarin.android project, there are many ways to add a custom control to the activity category of the actual processing user interface, and the example in this article uses a custom control in the project using a direct addition to the Axml archive.

    • Main.axml

      <CustomControlSample.CountMeter    android:id="@+id/MyCountMeter1"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_marginTop="20dp" />

After adding the custom control to the project by joining the Axml file, in the actual processing of the user interface activity category, the control can be acquired in the same way as the built-in control via the Findviewbyid method, and the control provides methods, properties, events, To provide a more user-friendly interface.

    • MainActivity.cs

      [Activity(Label = "CustomControlSample", MainLauncher = true, Icon = "@drawable/icon")]public class MainActivity : Activity{    // Fields    private int _count = 0;    // Methods    protected override void OnCreate(Bundle bundle)    {        // Base        base.OnCreate(bundle);        // View        this.SetContentView(Resource.Layout.Main);        // CountMeter        var countMeter1 = FindViewById<CountMeter>(Resource.Id.MyCountMeter1);        // UpButton        var upButton = FindViewById<Button>(Resource.Id.UpButton);        upButton.Click += delegate        {            _count += 10;            countMeter1.Count = _count;        };        // DownButton        var downButton = FindViewById<Button>(Resource.Id.DownButton);        downButton.Click += delegate        {            _count -= 10;            countMeter1.Count = _count;        };    }}

Sample Download

Sample program code: Click here to download

[Xamarin.android] Custom controls

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.