Click here to Skip to main content
15,881,424 members
Articles / Mobile Apps / Android
Tip/Trick

Creating and Invoking an Activity in Droidio (Android Studio)

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
19 May 2014CPOL3 min read 18.4K   10  
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 <appname>\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:

Image 1

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:

XML
<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:

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

...with:

XML
<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:

Java
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:

Java
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:

Java
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:

XML
<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:

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

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

Java
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:

Image 2

License

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


Written By
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

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, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
-- There are no messages in this forum --