Click Event in Android App Using C# with Xamarin

    Today I will show you how to write simple android app. In this tutorial you can learn how to create Event in android using c# with xamarin.
Steps

  • ·         Create new project.

  •           Expand resource folder
  •        Click on layout folder
  •        Double click Main.axml file

  • ·         Click source

Paste blow code in source.
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
    android:orientation=vertical
    android:layout_width=match_parent
    android:layout_height=match_parent>
    <Button
        android:text=Click Me
        android:layout_width=match_parent
        android:layout_height=wrap_content
        android:id=@+id/button1 />
    <Button
        android:text=Sum
        android:layout_width=match_parent
        android:layout_height=wrap_content
        android:id=@+id/button2 />
    <Button
        android:text=Substract
        android:layout_width=match_parent
        android:layout_height=wrap_content
        android:id=@+id/button3 />
</LinearLayout>

Open MainActivity cs file  and paste below code.

FindViewById method  – This method finds a view that was identified by the id attribute from the XML that was passed in Activity.OnCreate(Bundle).



protected override voidOnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            // Set our view from the “main” layout resource
            SetContentView (Resource.Layout.Main);
            Button clickbtn = FindViewById<Button>(Resource.Id.button1);
            Button sumbtn = FindViewById<Button>(Resource.Id.button2);
            Button subbtn = FindViewById<Button>(Resource.Id.button3);
            clickbtn.Click += btn_click;
            sumbtn.Click += sumbtn_click;
            subbtn.Click += subbtn_click;
        }
        private voidbtn_click(object sender, EventArgs e)
        {
            Toast.MakeText(this, “Click me”, ToastLength.Short).Show();
        }
        private voidsubbtn_click(object sender, EventArgs e)
        {
            Int32 a = 26, b = 15,c=0;
            c = a – b;
           Toast.MakeText(this, “substract “ + a + ” – “ + b + “=” + c,                                  ToastLength.Short).Show();
        }
        private voidsumbtn_click(object sender, EventArgs e)
        {
            Int32 a = 10, b = 15, c = 0;
            c = a + b;
            Toast.MakeText(this, “Sum  “ + a + ” + “ + b + “=”  + c,                                     ToastLength.Short).Show();
        }



Leave a Reply

Your email address will not be published. Required fields are marked *