Introduction
The first part discussed about the tools, project files and other details of Android project solution. In this part, the topics that I will be covering are:
- Activity
- Event handling
- Menus
- Passing of data between activities
Activity
An activity is like a single screen in the Android which allows the user to interact with the application. Multiple activities can be made to work together to provide a user a seamless experience to the user but each activity can be independent of the other. As discussed in Part I, activity contain a .java file and a .xml file, similar to a structure of ASP.NET where for a web page, we have a .aspx page and .aspx.cs page. Though Android does not have a concept of code behind, we can safely assume .java class page to be code behind. A webform inherits from Page
class as it is the base class for all the webforms, similarly “Activity
” class is the base class for all the Activity.
Similar to webforms, activities also handle event of controls within the activity. Like page life cycle, we also have Activity life cycle. As we handle each event of the page lifecycle, we can do the same in activity also. Below items list down the lifecycle of an activity.
Event | Description |
onCreate | First method to be called when an activity is created |
onStart | Called when activity is becoming visible to the user |
onResume | This method is called when activity will start interacting with the user |
onPause | Called when activity is not visible to the user |
onStop | Called when activity is no longer visible to the user |
onRestart | Called after your activity is stopped, prior to start |
onDestroy | Called before the activity is destroyed |
There are few basic things that need to be understood in Android which are not there in ASP.NET. The first thing is that like whenever an Activity is sent as a background like users switch to other application or make a phone call, the activity’s OnStop
event is called. Once the application is back in foreground, the Onstart
event is called again. This particular event handling is specific to Android application when compared to ASP.NET. Like Page_load
or page_init
event in ASP.NET for an Android activity, we have onCreate()
event which is the first event that gets called when an activity is called for the first time. The below diagram shows the lifecycle and events of Android activity.
Events
Handling events of controls is pretty simple in Android as they are in ASP.NET, however Android allows us different ways to handle events. One way of handing events is similar to ASP.NET where the callback method name is hardcoded on the attributes of the command button. The second method is to create an object of the same type of the control for which event handlers need to be implemented, use the setOnClickListener
method of this object to specify how the event has to be handled. Final method is by inheriting the Activity
from the “OnClickListener
” class, override the onClick
method in the class, in this method identify which control initiated the event by using the “id
” property and then handle it.
In the attached project, there are two buttons in the MainActivity
. First button handles the event by providing the method name to be called when clicked on the attribute of onClick
method of the XML file very much similar to what happens in ASP.NET.
activity_main.xml
<button....
....
....
android:onClick="showMenu"
/>
Here, the method to be called on the button click is set on design time. The method showMenu()
is declared in the corresponding “MainActivity.java” , in our case on click of this button the Pop up menu is shown.
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
popup.setOnMenuItemClickListener(MainActivity.this);
popup.inflate(R.menu.popup_menu);
popup.show();
}
The second button implements the event handler by providing the method name to be called at run time instead of design time. At the onCreate
event, an object of type Button
is created and its setOnClickListener
method is set to the method that needs to be called after click.
Button button1;
button1 = (Button) findViewById(R.id.button_menu);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showMenu(v);
}
});
PS: Note that I have commented this code in the demo project to avoid the confusion in the functionality.
For the third method, we implement the OnClickListener
class as a part of our Activity
, the resulting code would look like this:
public class EventActivity extends Activity implements View.OnClickListener{
.....
.....
}
Once we have implemented OnClickListener
, it requires us to implement the onClick()
method. In this method, we can get the id
of that control for which the event callback was triggered and then we can handle the required functionality on that control.
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.button_event:
Toast.makeText(getApplicationContext(), "Event handled... ", Toast.LENGTH_LONG).show();
}
Once the OnClick
method is overridden, we need to tell the control which method to call when it's clicked, this is done by creating an object of that control and setting its click listener by using the "setOnClickListener
" method. This is done on the onCreate
event of the activity as shown in the code below. This method of event handling is preferred as it allows us to handle all the event callbacks in one area.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
Button button1;
button1 = (Button)findViewById(R.id.trfActivity);
button1.setOnClickListener(this);
...
...
}
Menu
In ASP.NET, we built menus using the menu control provided in VS or by using numerous JavaScript menus that are available or even build one. But Android already has a built in support for menus. Currently, there are 3 different types available. All of them are discussed below.
Options Menu
This is the primary collection of menu items for an activity. It's placed where actions have a global impact on the app, such as "Search," "Compose email," and "Settings". This is the most common and simple of all the menus to implement. This is the same menu which will be displayed when we click on the menu button on the phone. This menu is pretty similar to the ASP.NET menus. In the menu_main.xml file, specify all the menus that need to be displayed.
<menu xmlns:android</code>="http://schemas.android.com/apk/res/android"
<code>xmlns:app</code>="http://schemas.android.com/apk/res-auto"
<code>xmlns:tools</code>="http://schemas.android.com/tools"
<code>tools:context</code>=".MainActivity">
<item android:id</code>="@+id/action_settings"
<code>android:title</code>="@string/action_settings"
android:orderincategory="100" app:showasaction="never" />
<item android:id</code>="@+id/start_game" android:title="@string/start_game" />
<item android:id</code>="@+id/game_help" android:title="@string/game_help" />
</menu>
Loading of this menu is taken care by onCreateOptionsMenu
method. This is provided by default in the Activity
.class file.
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
Context Menu
This is a floating menu and made to appear when the user long clicks on an element of an activity. It helps in providing action to a particular selected element or a context frame. This type of menu is used when we want to provide a menu on some views (aka controls in ASP.NET). If a menu item has to be shown on some elements/views, then we can use this menu. This type of menu can be activated in most of the controls. To create a context menu on the onCreate
event, call the “registerForContextMenu
” with the id of the control for which menu has to be displayed.
registerForContextMenu(textViewMenu);
Then, override the onCreateContextMenu
method which will actually create the required menu.
@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo info)
{
super.onCreateContextMenu(menu,v,info);
menu.setHeaderTitle("Select One Action");
menu.add(0,v.getId(),0,"Search For Details");
menu.add(0,v.getId(),0,"Call On This Number");
}
Popup Menu
This type of menu is a modal menu which is anchored to the specified View. The menu is mostly displayed below the anchor view if there is a space or above it. It’s mostly used in cases where we have to provide users options of further actions on a specific content on a screen. The first step is to identify the view (again control in ASP.NET) which will display the menu. Menu items are to be put in an XML file and on click event of the view, we call the click event handler to fill the menu.
public void showMenu(View v)
{
PopupMenu popup = new PopupMenu(this, v);
popup.setOnMenuItemClickListener(MainActivity.this);
popup.inflate(R.menu.popup_menu);
popup.show();
}
Once the menu is displayed, PopupMenu.OnMenuItemClickListener
needs to be registered so that the click event in menu items can be handled.
Passing of Data Between Activities
When there are multiple activities in the application, there are chances that sometimes data from one activity needs to be passed to other activity. In ASP.NET, we have Query string, Sessions variable, cookies, etc.. to handle this situation, in Android this is achieved by Intent
object. Intent
object has to be passed with the class which needs to be called along with data as a parameter to the intent.putExtra
method.
public void sendMessage(View vw)
{
Intent intent = new Intent(this,EventActivity.class);
EditText editText=(EditText)findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}
The startActivity
method which has to be called for starting the other activity, once the other activity is loaded we use can recreate the Intent
object and then retrieve the values passed to this new Activity.
Conclusion
The intention of this article was not to go in details of how to implement the discussed topics in details, but to compare the features of ASP.NET and then find an equivalent feature in Android to achieve it. I have not covered all the topics, but I tried to cover few ones which I thought are required for initial understanding of Android development.