In an Android application, how do you start a new activity (GUI) when a button in another activity is clicked, and how do you pass data between these two activities?
Intent i = new Intent(firstactivity.this, secondactivity.class);
startActivity(i);
Starting an activity from another activity is very common scenario among android applications.
To start an activity you need an Intent object.
An intent object takes two parameter in its constructor
Example:
So for example,if you have two activities, say HomeActivity
and DetailActivity
and you want to start DetailActivity
from HomeActivity
(HomeActivity-->DetailActivity).
Here is the code snippet which shows how to start DetailActivity from
HomeActivity.
Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);
And you are done.
Coming back to button click part.
Button button = (Button) findViewById(R.id.someid);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(HomeActivity.this,DetailActivity.class);
startActivity(i);
}
});
Take Button in xml first.
<Button
android:id="@+id/pre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"
android:text="Your Text"
/>
Make listner of button.
pre.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
Easy.
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
Extras are retrieved on the other side via:
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.
}
Don't forget to add your new activity in the AndroidManifest.xml:
<activity android:label="@string/app_name" android:name="NextActivity"/>
Although proper answers have been already provided but I am here for searching the answer in language Kotlin. This Question is not about language specific so I am adding the code to accomplish this task in Kotlin language.
Here is how you do this in Kotlin for andorid
testActivityBtn1.setOnClickListener{
val intent = Intent(applicationContext,MainActivity::class.java)
startActivity(intent)
}
Place button widget in xml like below
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
/>
After that initialise and handle on click listener in Activity like below ..
In Activity On Create method :
Button button =(Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new
Intent(CurrentActivity.this,DesiredActivity.class);
startActivity(intent);
}
});