- To add a new activity, follow the methods answered in this question. This way you will create a new activity without adding it to the Manifest manually. [every activity needs to be listed in the
AndroidManifest.xml
].
Say you create a new activity names Activity2.java
. To add the new layout to the new activity, add a new xml file to res/layout
folder, say activity2.xml
[where you define your new activity's layout]
To link the new layout to the new activity, include this line in your newly created Activity2.java
setContentView(R.layout.activity2);
So it will look like this:
public class Activity2 extends Activity{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
}
}
2 . Now if you want to send some data from your Activity1.java
to Activity2.java
, you need to use Bundles
.
So, if you want to send say a String
from Activity1
, do the following in Activity1.java
:
Intent nextActivity = new Intent(this, Activity2.class);
Bundle passData = new Bundle(); //to hold your data
passDataBndl.putString("fname", fname); //put in some String. the first parameter to it is the id, and the second parameter is the value
nextActivity.putExtras(passDataBndl); //Add bundle to the Intent
startActivityForResult(nextActivity, 0); //Start Intent
To recieve data in your Activity2.java
do the following (say, onCreate()
)
Bundle params = this.getIntent().getExtras(); //gets the data from the Intent
String firstName = params.getString("fname"); //gets value of fname