Sunday, June 15, 2014

Switching Activities in Android (tutorial 03)

New activity when the user clicks the button. Here I will improve last sample code

1. Create a new activity

image

2. You can see new UI for 2nd activity and then we change string value as below

image

3. In MainActivity.java we can added below line to switch activity. (there are few ways to achieve it, this only one way)

1 Intent intent = new Intent(MainActivity.this,SecondActivity.class);
2 startActivity(intent);

[Note]


An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.


4. Just run app and see it. (click back button to go to previous activity)


Screenshot_2014-06-15-19-07-14[1]Screenshot_2014-06-15-19-07-22[1]


Now we will try to pass message from one activity to second activity


[NOTE]


An intent not only allows you to start another activity, but it can carry a bundle of data to the activity as well.


1 //passing string
2 Intent intent = new Intent(MainActivity.this,SecondActivity.class);
3 intent.putExtra(EXTRA_MESSAGE, name);
4 startActivity(intent);

 


Then we will retrieve data


1 // Get the message from the intent
2 Intent intent = getIntent();
3 String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

Fragment


A Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments. Android introduced fragments in Android 3.0 (API level 11).  Next post will content more about Fragment with some sample coding.

No comments:

Post a Comment