Toggle Button using Mono for Android

Toggle Button : Displays checked/unchecked states using a light indicator

Step for creating Toggle Button

  1. Start new Android application

    create android application
     
  2. Go to Main.axml and make following changes

    main.axml layout in android

    <?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"
        >
      <
    ToggleButton android:id="@+id/togglebutton"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textOn="Sound on"
              android:textOff="Sound off"/>
    </LinearLayout>
     
  3. Go to Activity1.cs class make following changes

    activity1.cs class in android

        public class Activity1 : Activity
        {       
            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);
                
                SetContentView(Resource.Layout.Main);
                
                ToggleButton togglebutton = FindViewById<ToggleButton>(Resource.Id.togglebutton);
     
                togglebutton.Click += (a, b) =>
                {               
                    if (togglebutton.Checked)
                        Toast.MakeText(this, "Checked", ToastLength.Short).Show();
                    else
                        Toast.MakeText(this, "Not checked", ToastLength.Short).Show();
                }; 
            }
        }

    As above we create a toggle button and use If-else condition on button click event to check the state of button whether it is clicked or not and shows message and change the view of button according the state
     
  4. Run the application

    toggle button in android

    After click on button:

    toggle button in mono android

    Again click on button:

    toggle button in monoandroid
Thank You.....
Ebook Download
View all
Learn
View all