It’s really important for engineers who use Xamarin to develop Android app to know how to transfer Java code to C# code.
Recently I am trying to implement something in Xamarin.Android project (Not Forms) and I encountered lots of issues.
What I can find online is mostly Android native documents from Google. And I do find one sample project from Google that is implemented in Android Studio using Java.
So what I have to do is to understand how to transfer Java code to C# code, otherwise you will find it quite difficult to use pure Xamarin.Android project.
What’s the difficulty?
Although we always have a concept that Java has almost 80% simility with C#, maybe more. However, there are still lots of things that are different.
In this blog, I will use a Xamarin sample to demonstate how I transferred Java’s event handler which is also known as Listener to C#’s event handler. Also, I will show you in Xamarin.Android, how it’t different in Xamarin.Android and native Android for setting value for fields.
Events Handler transfer
First I will talk about Event Handler in Java and C#.
We all know that in Java, it will always use setXXXX to provide implementation or values for event or fields.
However, the tricky thing is that: in one Android activity, on the UI, you might have multiple same UI controls that have the same events to implement.
We can see from the above code. In Java or native Android development, the event is created by calling the setXXXXListener method and pass a newly instanted Listener instance into it. Then, you can override whatever events you’d like to implement within that Listener.
However, in C#, we do not have this kind of Listener, we can use event handler or delegates to do the same thing. In C#, the event is binding to the object as a Property.
So, if we are going to implement the same as the above Java code, we can do like below:
Done. And if you use VS Intelligence, you will also see when you are writing widthSeekBar.ProgressChanged +=, there will be some hint for you. You can simply press Tab and the method structure in the above code will be generated automatically for you. What is really good is that the name is also intelligent, it starts with WidthSeekBar.
Other similar point of this article
What I want to share here is that, the above apporach is almost everywhere between Java and C#.
For example, if you declare a field in Java, then each time you want to modify the value of that field, you have to call setXXXX() method to that object.
On the other hand, C# always implement the same as Properties.