Android Tutorial – Switch Between Activity With Android Button Click For Beginner

Seegatesite – continued on introduction android programming tutorial that I have discussed in previous articles, this time I will share android programming tutorial on how the button to switch between activity to another activity. In developing Android App we may be facing a situation where we need to move between the Activity (Screen) to another activity. Before further discussion, I will explain a little bit about the activity on android.

What is Activity on Android ?

Activity represents one screen with a user interface. For example, A Messaging application has activity inbox list, there is other activity such as create new message.

Each activity always begins with a callback method onCreate (). Sequence callback method from start activity until the end of the activity can be seen in the following diagram lifecycle activity below

Activity Lifecycle Android Tutorial Switch Between Activity With Button Click
Activity Lifecycle (source : http://developer.android.com)

Callback method defines an event, we don’t need to implement all the callback method. However, it is important and necessary to understand each function of the Callback method, so that our application can run your expectation.

onCreate() : This method was first called when the first activity begins.
onStart() : This method is invoked when the activity is already visible to the user.
onResume() : This method is invoked when the activity began to interact with the user.
onPause() : This method Called when the activity stops while not accept user input and does not execute any code.
onStop() : This method is invoked when the activity is not visible to the user.
onDestroy() : This method is called before an activity is disabled.
onRestart() : This method is invoked after the activity stopped and displayed again by the user.

Android Tutorial How to Switch Between Activity With Android Button

1. Create new project with name : SwitchActivity like following picture below

Create New Project Android Android Tutorial Switch Between Activity With Button

If you guys don’t know how to create a new project on android studio. please read my previous article Introduction Android Studio for Beginners.

2. Add new textView and buttons on the layout activity_main.xml or copy the following script on your activity_main.xml / content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.sigit.switchactivity.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First Activity"
        android:id="@+id/firstText" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First Button"
        android:id="@+id/button"
        android:layout_below="@+id/firstText"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

3. Create a new layout as second_activity.xml and copy the following script

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Second Activity"
        android:id="@+id/textView" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back Button"
        android:id="@+id/button2" />
</LinearLayout>

4. Then open MainActivity.java and copy the following script

package com.example.sigit.switchactivity; // change with your package name
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.content.Intent;

public class MainActivity extends AppCompatActivity implements OnClickListener {

    Button mybutton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mybutton = (Button) findViewById(R.id.button);
        mybutton.setOnClickListener(this);
    }
    public void onClick(View v){
        switch (v.getId()){
            case R.id.button:
                Intent i=new Intent(MainActivity.this, SecondActivity.class);
                startActivity(i);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Description :

– On line 16, add a new variable “mybutton” as a button
– On lines 20 and 21, to declare a variable mybutton with the button on activity_main.xml
– Script to open another activity found on line 27 and 28

Intent i=new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);

5. Create a new class named SecondActivity.java and copy the following script

package com.example.sigit.switchactivity; // change with your package name

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SecondActivity extends Activity{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);

        Button secondbutton = (Button)findViewById(R.id.button2);
        secondbutton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                finish();
            }
        });
    }

}

Description :

finish() function will close and return to the activity_main.xml

6. Add a new activity in android manifest as the following script

<activity android:name=".SecondActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

Description :

Each new activity to be accessed must be registered with the android manifest

Run App and get result like belowSwitch Between Activity Tutorial Android For Begginer

Thus article about Android Tutorial – Switch Between Activity With Android Button Click For Beginner, hope useful 🙂

The following two tabs change content below.
This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Leave a Comment

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

%d bloggers like this: