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"?> <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>
The simple use
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); in.putExtra("myKey", "new1"); startActivity(in);
Receiving a parameter
- 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); startActivityForResult(in, 0);
Returning a result
Intent in = getIntent(); in.putExtra("result", "some parameter"); setResult(RESULT_OK,in); finish();
Getting the result from the new activity
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d("Result",""+data.getExtras().get("result")); }
Man, this was very helpfull. Thanks a million for not being selfish and sharing this info.