Creating & managing activities in Android App

This simple tutorial shows you to create a method in Eclipse that allows you to move to a different activity within your Android app.

In this tutorial we will create 4 files. (main.xml,, second.xml,
The idea is simple, click a button on main screen and go to second screen.

Main files :
Add a button to your main.xml file and give it id button1.
In you file find onCreate method and add this code

    public void onCreate(Bundle savedInstanceState) {
        Button b = (Button) findViewById(;
        b.setOnClickListener(new OnClickListener() {
                     public void onClick(View v) {
                           startActivity(new Intent(MainActivity.this, Second.class));

So we can easily find button on our main screen using  findViewById method.
Then we add listener to a button and if someone click the button we lunch startActivity method.
startActivity method accept Intent(ourcontext, class we want to lunch) as a parameter.

Second files:
Now create second.xml and

In second.xml add another button so you can go back to your main screen and set id to back.
It is a good idea to use strings resources, so in strings addnew String MainMenu and add value  "Main".
 In your second.xml file add this to your button:


Add code in file:


       protected void onCreate(Bundle savedInstanceState) {
              // TODO Auto-generated method stub
              Button button = (Button) findViewById(id.back);
              button.setOnClickListener(new OnClickListener() {
                     public void onClick(View v) {

                                  startActivity(new Intent(Second.this, Main.class));

We added to file setContentView(R.layout.second), this is layout that our class will use(second.xml).

Now the last very important think is modifying the  AndroidManifest.xml

We have to add our activity:


Thanks for following tutorial.
Adam Bielecki


Post a Comment