Android – Opening a new screen
| Opening a new screen is fairly easy in android. This post will show you almost all you need to know about switching back and forth between screens in your Android application. |
Add all activities to manifest
- Each screen is usually an Activity.
- Each activity should be mentioned in the manifest file.
<?xml version="1.0" encoding="utf-8"?>The simple use
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aviyehuda.puzzle" android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name="MyActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MyActivity2" >
</activity>
</application>
<uses-sdk android:minSdkVersion="6" />
</manifest>
Intent in = new Intent(MyActivity.this, MyActivity2.class);
startActivity(in);
- Bear in mind that every time you will call the function startActivity(intent) a new instance of MyActivity2 will be created.
Passing a parameter
- In most times you need to pass a parameter to the new screen. You do that by using the function putExtra().
- This function
Intent in = new Intent(myactivity.this, MyActivity2.class);Receiving a parameter
in.putExtra("myKey", "new1");
startActivity(in);
- And of course you will need to receive that parameter on the other side.
String s= getIntent().getExtras().get("myKey").toString()Going back
- If you need to go back to the previous screen and terminate the current screen, than all you have to do is to use the function finish() from anywhere in the new Activity.
finish();Open for result
- When you need to open a new screen and get result back from it, than use the function startActivityForResult() instead of startActivity()
Intent in = new Intent(myactivity.this, MyActivity2.class);Returning a result
startActivityForResult(in, 0);
Intent in = getIntent();
in.putExtra("result", "some parameter");
setResult(RESULT_OK,in);
finish();
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("Result",""+data.getExtras().get("result"));
}
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)






Comments
Senthil Balakrishnan replied on Thu, 2010/12/02 - 12:37am
I had difficutly in passing a custom object between screens. What i udnerstood from the android documentation, the object need to implement Parcelable interface, after doing it the primitives in the object are accessible in the target activity but not objects/arrays.
public Intent putExtra (String name, Parcelable value)
What's your experience on this ?