Learn Android App Dev: Starting new Activity
Hey there! This is Amey Lokhande. In this post I will guide you on how to create a new activity in your app.
An activity represents a single screen with a user interface just like window or frame of Java.Android activity is the subclass of ContextThemeWrapper class. Multiple activities are used when the user wants to perform multiple tasks in the same application.
Here are the steps:
1) First of all, design the first activity of MainActivity layout by dragging a button in it to start the new Activity.
2. Now go to the app->Res->Layout folder. Right click on layout and create a new Blank Activity.
3. Now give an appropriate name to your activity. While creating the new Blank Activity, copy the package name from the Main activity. Now you will see two activities in your java and layout folder.
4. Now inside the app->manifests, open the AndroidManifest.xml file.
The AndroidManifest.xml file contains details of all the activities in your app.
5. Inside that file, add the details of your second activity. Add the name from the tools:context line from your Second_activity.xml file. And change the category to Default. If you dont get it, the details you need to add are highlighted in blue.
6. Now we have to write the code in MainActivity.java.
i) First of all, declare a button variable inside your MainActivity class.
ii) Then create a new Method which will be used to start the new Activity. Cast your button variable inside that activity.
iii) We will start the new Activity on button click event. This will be done by creating an object of the Intent class. Finally use the StartActivity method to start the new Activity. Inside the argument for StartActivity pass the intent object.
Here is a screenshot of the working app:
Java Code:
MainActivity.java:
package com.example.ameylokhande.appdev3;
import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button;
public class MainActivity extends AppCompatActivity { private static Button btn;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StartNewActivity(); } public void StartNewActivity(){ btn = (Button)findViewById(R.id.button); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent("com.example.ameylokhande.appdev3.second_activity"); startActivity(i); } }); } }
Thats all! Thanks for reading. Stay tuned for further updates.