Android activity – from one screen to another screen

In Android, an activity is represent a single screen. Most applications have multiple activities to represent different screens, for example, one activity to display a list of the application settings, another activity to display the application status.

Note
Refer to this official Android activity article to understand more about Android activity.

In this tutorial, we show you how to interact with activity, when a button is clicked, navigate from current screen (current activity) to another screen (another activity).

P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. XML Layouts

Create following two XML layout files in “res/layout/” folder :

  1. res/layout/main.xml – Represent screen 1
  2. res/layout/main2.xml – Represent screen 2

File : res/layout/main.xml


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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I&apos;m screen 1 (main.xml)"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click me to another screen" />

</LinearLayout>

File : res/layout/main2.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="I&apos;m screen 2 (main2.xml)"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

2. Activities

Create two activity classes :

  1. AppActivity.java –> main.xml
  2. App2Activity.java –> main2.xml

To navigate from one screen to another screen, use following code :


    Intent intent = new Intent(context, anotherActivity.class);
    startActivity(intent); 

File : AppActivity.java


package com.mkyong.android;

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

public class AppActivity extends Activity {

	Button button;

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

	public void addListenerOnButton() {

		final Context context = this;

		button = (Button) findViewById(R.id.button1);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

			    Intent intent = new Intent(context, App2Activity.class);
                            startActivity(intent);   

			}

		});

	}

}

File : App2Activity.java


package com.mkyong.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

public class App2Activity extends Activity {

	Button button;

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

}

3. AndroidManifest.xml

Declares above two activity classes in AndroidManifest.xml.

File : AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mkyong.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".AppActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:label="@string/app_name"
            android:name=".App2Activity" >
        </activity>
    </application>

</manifest>

4. Demo

Run application.

AppActivity.java (main.xml) screen is display.

android activity demo1

When above button is clicked, it will navigate to another screen App2Activity.java (main2.xml).

android activity demo2

Download Source Code

References

  1. Android activities example

104 comments on “Android activity – from one screen to another screen

  1. Can you help me this please. On a button click i want to perform activities one after other but it performs all activities simultaneously. For example I want to display next layout after completion of animation.But it directly displays layout.

  2. hi.. i am a beginner. i want to create 20 pages. i have a button, 3 radio buttons and a textview in all the pages i want to create. do i need an activity for all pages or can i create this in a single activity as layout is same

    1. Sure you can use only one activity for your 20 pages. When you create an intent to start the activity, you can use method putExtra on this intent to pass some data to your activity. Finally, in the activity, use getIntent() to get activity’s intent and use on it getExtra methods to obtain your data (for e.g. method getStringExtra if the expected data is a String value. You could then apply these values for objects of activity’s layout.

  3. I am beginner to android,here it is getting error like Error:(25, 44) error: cannot find symbol variable button1,please provide information

  4. Hey mkyong
    I am very much Thank full to you about above showed examples.
    My query is how to get alarm on full battery charge?
    Please give reply as fast as possible.

  5. from moving from main activity to activity 1 its working but when moviong from activity 1 to activity2 its not working and promting a message(unfortunately application has been stoped)

  6. Hi, thanks for the tutorial, im new to android programming. How can i kill/finish/destroy a layout login. Just like facebook app prevents you from login all the time

  7. This code worked perfectly! I had been struggling all day and using different codes but this one worked like a charm. Thank you!!

  8. Hello ,I have been watching your blog for various solutions , everything is best and clear solution.Iam a beginner for android devlopment , through this page i learnt activity and below are my questions
    Please clarify
    1.I have so many layouts so for each layouts should i create a activity.java file ?
    2.Can we parameterize somehow?

    Thanks

  9. i did like this ….but my app get crash when i run it 🙁

    import android.R;

    import android.app.Activity;

    import android.content.Intent;

    import android.os.Bundle;

    import android.view.View;

    import android.widget.Button;

    public class Activity1 extends Activity{

    Button button;

    protected void onCreate(Bundle savedInstanceState) {

    // TODO Auto-generated method stub

    super.onCreate(savedInstanceState);

    button =(Button)findViewById(R.id.button1);

    button.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View v) {

    Intent intent = new Intent(Activity1.this,Activity2.class);

    startActivity(intent);

    }

    });

    }

    }

  10. Hi,

    I am beginner to the Java programming and android …I am trying to create an app convertor which has 4-5 conversion money convertor, kgs to pound convertor..So, when I click on one conversion button it has to take me to the page pertaining to calculating the values….

    Actually before i had made an app which converts rupees to dollars..I am try use the same xml and java files here…I read tutorial and watched youtube and tried tht in my sdk but its not opening up anything so I do not which part is wrong or I made any mistakes in coding.. If any one out there can help it would be great.

    My code goes like this….MainActivity.java

    package com.example.converts;

    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Intent;

    import android.view.View;
    import android.widget.Button;

    public class MainActivity extends Activity implements View.OnClickListener
    {
    Button button2;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity1);
    button2=(Button)findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v){

    if(v.getId()==R.id.button2)

    {
    startActivity(new Intent(“com.example.converts.Main1″));
    }}
    });

    }
    }
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    }}

    My Main1 which I created has

    package com.example.converts;

    import android.os.Bundle;
    import android.app.Activity;
    import android.content.DialogInterface;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.*;

    public class Main1 extends Activity implements OnClickListener {
    TextView dollars;
    TextView euros;
    RadioButton dtoe;
    RadioButton etod;
    Button calculate;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    }
    public void onClick(DialogInterface arg0, int arg1) {
    // TODO Auto-generated method stub

    dollars = (TextView)this.findViewById(R.id.dollars);
    euros = (TextView)this.findViewById(R.id.euros);

    dtoe = (RadioButton)this.findViewById(R.id.dtoe);

    etod = (RadioButton)this.findViewById(R.id.etod);

    calculate = (Button)this.findViewById(R.id.calculate);
    calculate.setOnClickListener(this);
    }

    public void onClick(View v) {
    if (dtoe.isChecked()) {
    convertDollarsToEuros();
    }
    if (etod.isChecked()) {
    convertEurosToDollars();
    }
    }

    protected void convertDollarsToEuros() {
    double val = Double .parseDouble(dollars.getText().toString());
    // in a real app, we’d get this off the ‘net
    euros.setText(Double .toString(val*0.67));
    }

    protected void convertEurosToDollars() {
    double val = Double .parseDouble(euros.getText().toString());
    // in a real app, we’d get this off the ‘net
    dollars.setText(Double.toString(val/0.67));

    }

    }

    My activity_mail.xml file has code

    android:typeface=”sans”
    android:textStyle=”bold”

    activity1.XML has the following code

    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:paddingBottom=”@dimen/activity_vertical_margin”
    android:paddingLeft=”@dimen/activity_horizontal_margin”
    android:paddingRight=”@dimen/activity_horizontal_margin”
    android:paddingTop=”@dimen/activity_vertical_margin”
    tools:context=”.MainActivity” >

    So, please let me know what I am doing wrong..or what corrections I need to make to get this…

  11. when am download codes and made existing project in my android project its working.but i made cut copy your codes its not working. can u tell me the reason please and what are the thinks i need to correct?

  12. Hi,

    That was a useful explanation.

    I have a table in Excel. I should read the excel and create bar charts on screen.

    Statically, I am able to do this with excel file added as a resource to the package.

    But how do I read the Excel dynamically and I intend to update the Excel periodically.

    I can not use any databases.

    Instead of Excel, could the data be passed directly to all client devices using the application using XML?

    Thanks in advance,
    Mathan V.

  13. Thanks for the tutorial ! I’m a beginner and I find this lesson really interesting 🙂 But I have a question… Do you usually declare your Views in the XML document or in the Java document ? Or do we have to do it on both ? What if I want to add Views to my layout dynamically ? Do I still need to define them on the XML document ?

  14. What is intent filter do? And you included it for main activity only. Can you explain a little more on this?

    Thank you for a great site.

  15. Needs more explanation about whats going on with the codes, especially about the 2 intents defined in the manifest file..

  16. cool website it is very educational 🙂 it is very nice how you strip down the app to the bare minimun for the explanation , it gets rid of all the noise

  17. Thanks mkyong. This tutorial can’t be made any better. Simplicity.
    All those who get forced error after clicking the button in the first activity, don’t forget to change the AndroidManifest.xml… Change it and then see the brilliant output

  18. It looks like INTENT keeps the calling activity in the background. If an application needs to switch back and forth between two activities, is it going to create multiple instances of the activities? It looks like it is the case with the example code because if I switch back and forward between two activities 5 times and click the BACK button 10 times (5×2=10), you will see 5 instances of the two activities. How do I prevent the application from keeping an activity in the background more than once while switching between two activities? Thanks.

    1. Peter, if an application needs to switch back and forth between two activities, you may want to consider a single activity with a tabbed UI instead. I have this for a configuration screen…instead of having three separate activities, one for editing Mass Flow Controllers, one for Robot Coordinates and the third for power supply constants, I have one configuration screen and three tabs.
      Much cleaner, but it’ll depend on your situation.

  19. Hello, Im having a hard time trying to figure this out:

    I need multiple buttons that will move to different activties and the first one is working thanks to this great tutorial!

    I did the third (page1english) Class and Layout.xml and they are indentical at the second one (page1portuguese)
    Im using ImageButtons instead of the normal one, but the first one is working so no problem with that… can you take a look at my code? Thanks!

     package com.example.panel;
    
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.widget.ImageButton;
    import android.view.View;
    import android.view.View.OnClickListener;
    
    public class MainActivity extends Activity {
    	
    	ImageButton button1;
    	ImageButton button2;
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		addListenerOnButton();
    		
    	}
    
    	public void addListenerOnButton() {
    		 
    		final Context context = this;
     
    		button1 = (ImageButton) findViewById(R.id.imageButton1);
     
    		button1.setOnClickListener(new OnClickListener() {
     
    			
    			public void onClick(View arg0) {
     
    			    Intent intent = new Intent(context, Class_page1portuguese.class);
    			    startActivity(intent);   
    			
    			}
    			
    		});}
    		
    		public void addListenerOnButton2() {
    			 
    			final Context context = this;
    	 
    			button2 = (ImageButton) findViewById(R.id.imageButton2);
    	 
    			button2.setOnClickListener(new OnClickListener() {
    	 
    				@Override
    				public void onClick(View arg0) {
    	 
    				    Intent intent = new Intent(context, Class_page1english.class);
    				    startActivity(intent);   
    				   				    
    				}
    	 
    			});
    		
    		
    	}
     
    }
     
     XML here 
  20. hi

    i have a problem

     
    
    package ir.example.test2;
     
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.widget.Button;
    import android.view.View;
    import android.view.View.OnClickListener;
     
    public class AppActivity extends Activity {
     
    	Button button;
     
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main1);
    		addListenerOnButton();
    	}
     
    	public void addListenerOnButton() {
     
    		final Context context = this;
     
    		button = (Button) findViewById(R.id.button1);
     
    		button.setOnClickListener(new OnClickListener() {
     
    			@Override
    			
    			/* in next line i have a error
    			 
    			  
    			 
    			  Multiple markers at this line
    	- implements android.view.View.OnClickListener.onClick
    	- The method onClick(View) of type new View.OnClickListener(){} must override a superclass 
    	 method
    			 
    			*/ 
    			public void onClick(View arg0) {
     
    			    Intent intent = new Intent(context, App2Activity.class);
                                startActivity(intent);   
     
    			}
     
    		});
     
    	}
     
    }
    
    
    
     

    thanks

    1. Right click you project folder -> Properties -> Java Compiler -> Compiler compliance level -> from 1.5 to 1.6

      That should work. I was having the same problem. Cheers!

    2. Thanks. Just in my second assignment. was stuck with connecting 2 activities. Your page has very neatly and clearly written information.

  21. Hello,

    All your tutorials are really very helpful to the beginners. Thanks..
    I performed in the same way as you have guided but unfortunately when i click the button, its getting closed forcibly i.e. it say the app appname(process com.example.appname) has stopped unexpectedly. Please try again.
    Can you please figure out what has went wrong?? It’ll be of great help.
    Looking forward for your reply.

    Thanks

    1. Hi,

      I am having the same issue. When I click on the button in the first activity, the whole app stops with the error and closes. Have you figured out what is wrong?

      Thanks!

  22. i have a probleme with this when i click the button its say unfortunataly…. so sad i cant creat another screen in a click button i tried a lot but nothing 🙁

  23. Hi all,i’m a beginner in android programming,just wanted to ask,if i wanted to create a button in screen2 that leads me to screen3,what do i put in the following:

    For the android.intent.action.MAIN,do i keep it like that for screen or do i change it to something else? Same question for the android.intent.category.LAUNCHER,much thanks will be appreciated 🙂

  24. I have one activity say UserList and second one is chatwindow.
    UserListActivity contains events which are executed on threads to update list of available users and take care send recieve message.
    when user clicks on user in list new window should open in tab.
    when message recieved from server it should be shown in chat window.
    I could i achive this?
    How i can desing the screen and manage the single user activity can handle multiple chatwindow activities of same type.
    Any help would be highly appriciated.

  25. Amazing tutorial, pretty simple and nicely explained. It works perfect except i couldn’t run the sourcecode.zip properly, but writing it by myself helped me understand it, because I’ve been wondering why you defined and object button in App2Activity.java. Nevermind, thanks again, the best android tutorial for activity!

  26. When i click the button, it is not taking me to next page... 
    Here is my code:
     
    
    package com.application.liveapps;
    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.widget.Button;
    import android.view.View;
     
    public class launch1 extends Activity {
     
    	Button button;
     
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.launch);
    		addListenerOnButton();
    	}
    	
    	public void addListenerOnButton() {
    		final Context context = this;
    
    		button = (Button)findViewById(R.id.button1);
     
    		button.setOnClickListener(new View.OnClickListener() {
    			
     public void onClick(View view) {
    
    
    Intent i = new Intent(context, Next2.class); //next2.java
                             startActivity(i);
     
    			}
     
    		});
     
    	}
     
    }
    
    1. pre lang=”language”>
      package com.application.liveapps;
      import..
      import..
      import ..
      import android.view.View.OnClickListener; (<—"Add this")

      public class launch1 extends Activity {
      //more code

  27. Tutorial is great help, I downloaded code and manged to run it. I had one doubt.how this xml files get mapped to activity classes?

    Basically how AppActivity.java —> main.xml
    App2Activity.java —-> main2.xml

    I did not notice anywhere we specifying this mappping.

  28. Very, very useful to a beginner like me who is struggling with people assuming I already know more than I do. Keep it up buddy!

    Thanks,

    John

Leave a Comment

Your email address will not be published. Required fields are marked *