Sunday, 4 January 2015

Start a new Activity in Android

I will be showing how to start a new activity in Android with Android studio. Firstly, this post assumes Android studio is already installed on your machine and a new project has already been setup with a Black Activity.

My activitiy_main.xml layout has one button with the id "button" with the text "Start new Activity". This button will open up a new Activity when it is clicked.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start new Activity"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

In my MainActivity.java file I have added a click event listener to the button. Inside my onClick function I have used an Intent Object. An Intent object "provides runtime binding between component" which basically means you can use it to pass data between activities. The intent has two parameters, the first is the current activity and the second is the Activity to be started. The "SecondActivity.class" will be created in the next step.

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

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

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

            }
        });
    }
} 

To create the secondActivity, in your Project panel, right click on the java folder and select New > Activity > Blank Activity. Give the activity name: "SecondActivity" Android studio should automatically fill in the other fields for you. Click Finish to add the SecondActivity to the project.

Run the App and click the "Start new Activity" button. The new activity will open up.

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP