Android – Creating a new activity in Eclipse [duplicate]

Ok. Being a newbie myself I think the above two answers are thinking too much. He’s asking very simply how to create a new activity in Eclipse.. I think this is what he wants:

A new Activity in Eclipse is actually a Class.

You would doubleclick ‘src’ on the left side in the Package Explorer, then highlight your ‘com.’ name, right click, select ‘New’ and then select ‘Class’. Enter the Name as NewActivity and set the Superclass to android.app.Activity, then hit Finish.

When the NewActivity.java file opens up it should look like this:

package com.example.yourappname;

import android.app.Activity;

public class NewActivity extends Activity {

}

You can leave the Superclass blank and add extends Activity to the code itself if you prefer.

The final step is adding the Activity to your Manifest. So doubleclick AndroidManifest.xml to open it up and then click the ‘Application’ tab on the bottom. Next to the ‘Application Nodes’ box, click ‘Add’. Highlight ‘Activity’ (the square box with a capital A) and click ‘Ok’. Now look for the ‘Attributes for Activity’ box and enter a Name for the Activity and precede it by a period. In this example you’d enter ‘.NewActivity’.

And then you can add your onCreate() code so it looks like this:

public class NewActivity extends Activity {

     @Override
     public void onCreate(Bundle savedInstanceState) {         

        super.onCreate(savedInstanceState);    
        setContentView(R.layout.main_view);
        //rest of the code
    }
}

main_view would be your main view xml file, main_view.xml, that you would create in your layout directory.

To call the new Activity, your Intent in the code (in a different Activity) to start a new Activity looks something like this:

Intent startNewActivityOpen = new Intent(PresentActivity.this, NewActivity.class);
startActivityForResult(startNewActivityOpen, 0);

And that’s it, you have the code to call the new activity and you created it. I hope this helps someone.

Leave a Comment