Android Studio: Develop the Application

This post is a follow on to Android Studio Getting Started. It explains how to localize text, change the default HelloWorld! text, add a button, and add a second action that defines what happens when the user clicks the button.

  1. Localizable Strings (String Theory)
  2. Change the Default Text
  3. Add a Button
  4. Add a Second Activity
  5. Provide Main Activity Button Action
  6. Fix Package Import Errors
  7. Run the Application
  8. Reference: Full MainActivity.java Code

1. Localizable Strings (String Theory)

The strings.xml file in your project enables you to define your application-specific string resources in one file. You reference the string resources to associate application text with user interface elements. Keeping string resources in a separate file enables you to reference all of your text strings from one place, and to easily hand this file to the localization team for translation.

Strings.xml

To view the strings.xml file:

  1. Switch the left panel to Project view.
  2. In the left panel under app > src > main > res > values locate the strings.xml file and double-click to open it.
  3. Note that there are two string resources already in there, app_name and action_settings. These string resources were added when you created the project.
<resources>
    <string name="app_name">MySimpleApp</string>
    <string name="action_settings">Settings</string>
</resources>

The app_name resource is the name you provided when you created the project and named it MySimpleApp. The action_settings resource is the name of a stub Settings menu provided in the default project. In Section 7. Run the Application, you can see a screen shot of the app with the Settings menu stub displayed.

Find Usages

You can easily find where any resource, widget, variable, class, and so on is used in Android Studio.

  1. In the open Settings.xml file, highlight what you want to find and Press Alt + F7, or in the action_settings line, right-click anywhere on the line.
  2. In the Find Usages panel, look for a gray bar that highlights where the action_settings resource is used.
  3. Double-click the highlighted line:
    8 android:title=”@string/action_settings”. This opens menu_main.xml in Android Studio.
  4. In menu_main.xml with the Design tab in the lower-left corner selected, you can see the string Settings in the top-right area of the design below the MySimpleApp app_title.

2. Change the Default Text String

The default application from Android Studio Getting Started has one text string: Hello World! The following steps explain how to internationalize and change the Hello World! string text. Internationalization is a two-step process:

  1. Add string resources to strings.xml
  2. Use @string/<string resource> notation within the app to reference the string resources in strings.xml

Add String Resource

Add the following resource to strings.xml:

<string name="simple_app">I am a Simple App!</string>

Reference the String Resource

Reference the simple_app string resource from a TextView widget as follows:

  1. Click the content_main.xml tab.
  2. Select the Design button in the lower-left corner.
  3. Select and drag Hello World! from the upper-left corner of the design to the center.
  4. With the Hello World! text selected, locate the Properties panel.
  5. Enter textView for the ID.
  6. Below under the TextView heading in the Properties panel type @string/simple_app into the text field and tab out of the field. This references the simple_app string resource, which changes the text.

    Screen Shot 2016-09-15 at 8.19.43 AM.png
    Put the @string notation in the text field under TextView as shown.
  7. Select  the Text button to display the xml form of content_main.xml.
  8. In the android:text line, you should see @string/simple_app:

content_main.xml:

If you don’t see an @ sign on the android:text line, single-click inside the quotes.

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:text="@string/simple_app" />

3. Add a Button

In this section you add a Next Page button to the I am a Simple App! screen that takes the user to the second page of the application.

ADD STRING RESOURCE

Add the following resource to strings.xml:

<string name="next_page">Next Page</string>

Reference the String Resource

  1. Click the content_main.xml tab.
  2. Select the Design button in the lower-left corner.
  3. In the Palette menu, find Button (under the heading Widgets).
  4. Click and drag the Button below your I am a Simple App message and center it.
  5. With the button selected, find the Properties menu and in the TextView section for the text field type @string/next_page, and tab out of the field.
  6. Check the ID field at the top of the Properties menu, and if you do not see button in the ID field, enter it and press Tab. In Section 5, you add code that uses the button ID to define the action for this button.

content_main.xml:

If you don’t see an @ sign on the android:text line, single-click inside the quotes.

<Button
    android:text="@string/next_page"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="72dp"
    android:id="@+id/button2"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />

The at sign (@) is required when you are referring to any resource object from XML. It is followed by the resource type (id in this case), a slash, then the resource name (next_page).

The first time you create a resource, put the plus sign (+) before the resource type. When you compile the app, the SDK tools use the ID to create a new resource ID in your project’s R.java file that refers to the EditText element. You do not need to add a plus sign for concrete resources such as strings or layouts. The R.java file is here:

MySimpleApp > app > build > generated > source > r  > debug > com.example.mysimpleapp.test > R

Resource Objects

A resource object is a unique integer name that’s associated with an app resource, such as a bitmap, layout file, or string.

Every resource has a corresponding resource object defined in your project’s R.java file. You can use the object names in the R class to refer to your resources, such as when you need to specify a string value for theandroid:hint attribute. You can also create arbitrary resource IDs that you associate with a view using theandroid:id attribute, which allows you to reference that view from other code.

The SDK tools generate the R.javafile each time you compile your app. You should never modify this file by hand.

For more information, read the guide toProviding Resources.

The plus sign (+) before the resource type is needed only when you’re defining a resource ID for the first time. When you compile the app, the SDK tools use the ID name to create a new resource ID in your project’s R.java file that refers to the EditText element. With the resource ID declared once this way, other references to the ID do not need the plus sign. Using the plus sign is necessary only when specifying a new resource ID and not needed for concrete resources such as strings or layouts. See the sidebox for more information about resource objects.

4. Add a Second Activity

When the user clicks the Next Page button, the second activity displays. It has two string resources: the second activity name and the message that displays to the user.

ADD STRING RESOURCE

This is the message that displays on the second page when the user clicks the Next Page button. Add the following resource to strings.xml:

<string name=”second_page_message”>I am the Second Page!</string>

Create Second Page

The second page is a second activity component.

  1. Towards the top of the project’s file system tree, right-click app.
  2. In the drop-down menu, select New > Activity > Basic Activity.
  3. Change the name of this activity to SecondActivity and click Finish. Android Studio creates the following files: SecondActivity.java, activity_second.xml, and content_second.xml. Also, Android Studio adds the following string resource to strings.xml:
    <string name="title_activity_second">SecondActivity</string>
  4. Navigate to app > src > main > res > layout  and double-click content_second.xml to open it.
  5. Click the Design button in the lower-left corner.
  6. In the Palette under Widgets, drag a TextView to the center of the layout.
  7. With the Text View selected, find the ID field in the Properties menu, and note that it is set to textView2 to distinguish it from the TextView in content_main.xml.
  8. With the Text View selected, find the text field in the Properties menu, and type @string/second_page_message.
  9. Click the Text button to view the XML version of content_second.xml.

content_second.xml:

If you don’t see an @ sign on the android:text line, single-click inside the quotes.

  1. <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        android:text="@string/second_page_message"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

5. Provide Main Activity Button Action

Now that you have a button in the main activity, you need to go to MainActivity.java and implement the button’s behavior.

  1. Open MainActivity.java.
  2. Find the onCreate method and add the following code to the end of it.This code adds the Button as part of the initial layout when the app displays.
    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
    //This line is red to indicate an error until you add the
    //launchSecondActivity method in the next step.
        launchSecondActivity();
      }
    });
  3. Add the following method to the end of the MainActivity class. This method provides the implementation of the launchSecondActivity method called in the button’s onClick method.The launchSecondActivity method creates an Intent object for SecondActivity. The code uses the Intent object to start the second activity. An intent describes an action to perform on an activity. See Intents and Intent Filters and Common Intents.
    private void launchSecondActivity() {
      Intent intent = new Intent(this, SecondActivity.class);
      startActivity(intent);
    }

For reference, the full MainActivity.java code is provided in Section 8:

6. Fix Package Import Errors

When you added the additional code to MainActivity.java, Android Studio flagged some missing imports. To remove the import errors, you can either press Alt + Enter (or Option + Return on Mac) to import the missing classes, or you can set Android studio to add the imports as you work, as follows:

  1. Select File > Other Settings > Default Settings.The  Default Preferences screen displays.
  2. On the Default Preferences screen under Java, set the options as follows:Insert Imports on paste: All
    Show import popup: Checked
    Optimize imports on the fly: Checked
    Add unambiguous imports on the fly: Checked
    Show import suggestions for static methods and fields: Checked

Click Apply and OK.

Android Studio adds the missing imports. For reference, the following is the complete import list for this app:

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

7. Run the Application

  1. Select Tools > Android > AVD Manager.
  2. In Your Virtual Devices, do one of the following:
    1. Under Actions, select an existing virtual device by clicking the green arrow.
      or
    2. At the bottom of the screen, click Create Virtual Device and walk through the screens.
  3. Select Run > Run app. MySimpleApp displays in the emulator.
  4. Click the button to go to the second page in the second activity.
  5. Click the left arrow at the bottom-left of the emulator to return to the main activity.
Screen Shot 2016-09-08 at 8.03.03 AM.png
MySimpleApp running in the emulator with the Settings menu stub displayed

Note: If any of the text is incorrect, go back to content_main.xml or content_second.xml and verify that you put the @string notation into the correct text field.

8. Reference: Full MainActivity.java Code

package com.example.mysimpleapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                launchSecondActivity();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, 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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void launchSecondActivity() {
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }
}
Advertisements
Android Studio: Develop the Application

One thought on “Android Studio: Develop the Application

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s