Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Creating a new activity in Eclipse [duplicate]

Easy one.

I've gone through a few guides and tutorials, and they're quite clear on how to start an activity (with intent).

However, how do I create a new activity in Eclipse? I can probably do this by hand, but then I have to modify the R file, which is auto-generated, and add a new xml layout.

like image 654
Hein du Plessis Avatar asked Sep 11 '10 11:09

Hein du Plessis


People also ask

How to create new Activity in Android Eclipse?

In Eclipse, you can click on the "New" button on the toolbar. Under Android, select Android Activity, and run through the wizard. This is the best solution by far, since it lets you set up a layout and an Activity all in one, while also updating the Manifest for you.


1 Answers

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.

like image 191
ShadowGod Avatar answered Sep 27 '22 23:09

ShadowGod