Android load new activity
In Android, you can load a new activity using the Intent
class. Here are the general steps:
-
Create a new
Intent
object:Intent intent = new Intent(this, NewActivity.class);
Replace
this
with the current activity, andNewActivity.class
with the name of the new activity you want to load. -
Set any necessary data or flags on the
Intent
object:intent.putExtra("key", "value"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
You can add extra data to the
Intent
using theputExtra()
method, and set flags using thesetFlags()
method. -
Start the new activity using the
startActivity()
method:startActivity(intent);
This will load the new activity and display it on top of the current activity.
Here's a complete example:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a new Intent
Intent intent = new Intent(this, NewActivity.class);
// Set some extra data
intent.putExtra("name", "John");
// Start the new activity
startActivity(intent);
}
}
In this example, when the user clicks a button or performs some other action, the MainActivity
will create a new Intent
object and start the NewActivity
using the startActivity()
method.
You can also use the startActivityForResult()
method to start a new activity and receive a result back from it. This is useful when you need to perform some operation in the new activity and then return the result to the original activity.
For example:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a new Intent
Intent intent = new Intent(this, NewActivity.class);
// Start the new activity and request a result
startActivityForResult(intent, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
// Handle the result
String result = data.getStringExtra("result");
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
}
}
}
In this example, the MainActivity
starts the NewActivity
using the startActivityForResult()
method and requests a result with the requestCode
value of REQUEST_CODE
. The NewActivity
can then return a result using the setResult()
method, and the MainActivity
can receive the result in the onActivityResult()
method.