Click here to Skip to main content
Click here to Skip to main content

Creating and Invoking an Activity in Droidio (Android Studio)

, 19 May 2014
Rate this:
Please Sign up or sign in to vote.
How to create an Android Activity and its associated Layout file, then invoke (intent) them from another Activity

Creating an Android Activity in Droidio

With your project opens in Android Studio, right-click \app\src\main\java\<bla>.app and select New > Activity > Blank Activity.

You will be greeted, unsurprisingly perhaps, by the "New Blank Activity" dialog. Give the Activity a name, such as "DeliveryItemActivity".

As you do so, the Layout Name property below it will be automatically populated with an appropriate corresponding name, such as, in this case, "activity_delivery_item" (this layout file will have a .xml extension).

Your dialog will now look something like this:

Now mash the "Finish" button.

This will open the layout file in the <appname>\app\src\main\java\res\layout folder, with a default layout and one widget: a TextView with the all-too-typical "Hello world!" verbiage:

<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="hhs.app.DeliveryItemActivity">

    <TextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

To prevent an oncoming nervous breakdown, change this to something more interesting by opening the \app\src\main\java\res\values\strings.xml file and replacing that:

<string name="hello_world">Hello world!</string>

...with:

<string name="hello_world">You say Hello I say Goodbye Mr. Chips Ahoy Matey!</string>

Note: If you change the pre-defined "hello_world" string in this way, all subsequent Layout files will use your verbiage (instead of the boring-but-safe default "Hello World").

Now open the Activity you created in <appName>\app\src\main\java\<appname>\app\DeliveryItemActivity. You will see the basic default Activity code:

package hhs.app;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class DeliveryItemActivity extends ActionBarActivity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.delivery_item, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

You'll notice that the constructor contains this line:

        setContentView(R.layout.activity_delivery_item);

So, this Controller (the Activity) has set its View (the Layout file) to the expected one - the one we were just tweaking a bit. You could set it to some other view here easily enough:

        setContentView(R.layout.why_do_fools_fall_out_of_love);

Of course, for that to make sense (and to work), you will have to have created a layout (xml) file named, in this case, "why_do_fools_fall_out_of_love.xml"

And, in fact, that's part of the beauty of the MVC (Model/View/Controller) paradigm - you can swap out Views for a particular controller based on the user (based on what features they need or what features they have the right to access, for example), the device your app is running on, the state of the device (such as whether it currently has an Internet connection, or something else), celestial phenomena (just joking, but you get the picture), or what have you.

Instantiating the Activity/Layout from Another Activity

Now that we've got an Activity/Layout pair, we want to invoke/instantiate them from another Activity.

To do so, you might respond to an event, such as a button being clicked or tapped. So to demonstrate this, drag and drop a button onto your main Activity (or any other one).

Go to the Activity's layout file (such as activity_main.xml) and open it. Make sure you're in Design (not "Text") mode (toggle to the Design tab, if necessary, in the SE corner of Droidio's midriff). From Palette > Widgets, drag a button. To give it a reasonable name, now go into "Text" mode; locate the XML that describes the button you just added. It will look something like this:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bla"
        android:id="@+id/button2"
        android:layout_alignBottom="@+id/textView2"
        android:layout_alignRight="@+id/listViewXactionList"
        android:layout_alignEnd="@+id/listViewXactionList" />

Change the "text" and "id" properties to give your button a non-generic caption and name, such as:

android:text="Delivery Item"
android:id="@+id/buttonDeliveryItem"

Now open MainActivity, and add code like the following below the call to "setContentView()" shown earlier:

        Button button = (Button) findViewById(R.id.buttonDeliveryItem);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent delItemIntent = new Intent(MainActivity.this, DeliveryItemActivity.class);
                MainActivity.this.startActivity(delItemIntent);
            }
        });

...and voila! Run the app, mash the button, and the Activity you created shoves the previous Activity out of the way and takes over center screen:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

B. Clay Shannon
Publisher "Found in the Translation"
United States United States
I am the entire team at "Found in the Translation," which produces multilingual books (paperback and Kindle versions) such as "Don Quixote: In Spanish and English, Paragraph-by-Paragraph" among many others (English paired with not only Spanish, but also French and even Finnish). You can see all those books here: http://jsfiddle.net/clayshannon/pRgQL/75/
 
Personal web sites that I have created can be seen at http://usamaporama.azurewebsites.net and http://bigsurgarrapata.azurewebsites.net/ and http://www.awardwinnersonly.com
 
Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.
 
I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction: http://www.lulu.com/spotlight/blackbirdcraven
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 19 May 2014
Article Copyright 2014 by B. Clay Shannon
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid