What is an Activity in Android?
Activity is a single screen in Android. It is like a web page that has many elements in it. In Android there is a java/kotlin class and layout for an activity, the class takes care of creating a window for the layout you made. It is also responsible for controlling the layout. The layout on the other hand, is the UI of that window.
How To Start New Activity In Android?
To start new activity, you need to have a trigger for when the user clicks something. First, create an onClickListener
to a view or component you want to set as a trigger to start new activity. After that you must create an Intent. An Intent is an object that provides runtime binding between separate components, such as two activities. The Intent represents an app’s intent to do something. You can use intents for a wide variety of tasks, but in this blog, our intent starts another activity.
Button button = (Button) findViewById(R.id.button_next_activity);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(this,SecondActivity.class);
startActivity(intent);
}
});
On the code above, you can see that I created a button and add a click listener to it. When the user clicks the button it will trigger the code inside the onClick
method. I will now explain the code inside the method. Firstly, I instantiated an Intent and added some parameters. The first parameter is where the activity is, I put the this
keyword because it represent the class I’m in to. The second parameter is the new activity you want to start. Lastly, I called the startActivity
method and entered the intent I created as the parameter. The startActivity
method will start an instance of the new activity which is the SecondActivity
. Assuming that you have already created the second activity, then you have successfully started a new activity.
That’s it for today’s blog, I hope you learned something. Thank you!