Xamarin and the easiest ways to create events

Xamarin is a great tool for C Sharpers, and eventually it eases the pain. To be honestly I used to stuck while creating events for Android tools with Java, I am yet to understand what the hell is happening there. Its like a blackbox for me. I just memorize the code or Google for event snippets every time.

This is the sample code to trigger a button on Java

1
2
3
4
5
6
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
 public void onClick(View v) {
	 // Perform action on click
 }
});

But in Xamarin, the C# way is something like below

1
2
3
4
Button btn1 = FindViewById<Button> (Resource.Id.button2);
btn1.Click += delegate {
	//do something here
};

This above code is simply something easier to understand and make the blackbox transparent for the beginners. And notice the line numbers, only 4 lines yet getting the same job done. This is effective right?

For those who are familier with Windows development on C#, Xamarin provides another good old ways to create Events, yes this is a place we are getting the native C# events experience. It is,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
protected override void OnCreate (Bundle bundle)
{
	base.OnCreate (bundle);
	SetContentView (Resource.Layout.Main);
	//other things goes here..
	Button btn1 = FindViewById<Button> (Resource.Id.button1);
	
	//create a Click event for the button
	btn1.Click += DoSomeEvent;
}
private void DoSomeEvent(object sender, EventArgs ea)
{
	//Do something here 🙂
}

This is the beauty of Xamarin, the real tool to create native apps in C#.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s