Android Studio: create a first interactive userinterface

This tutorial shows how to build a simple userinterface with an inputfield (textfield) in which you can enter text, a button and a textview which displays a message. It can be used as a first project if you are starting to create Apps using Android Studio. It will show the basics of creating a userinterface and adding an eventhandler to a button. If you did not install & setup Android Studio yet, do that first.

Start a new Android Studio Project (either from the Welcome screen or via File > New > New project).
Choose “Basic Activity”. Click Next.
Type a name: eg. “Assignment1”. Check the language, it should be set to ‘Java’. Set the API Level to 19: API 19: Android 4.4 (KitKat).
Changing the Package name and the Location is optional.
Press Finish.

Create the userinterface

The userinterface already contains a textView with the text ‘Hello World!’. We are going to add an input field in which the user can type his/her name. When the user presses the Ok-button, a welcome text will be shown with the name read from the input.

In content_main.xml make sure you are at the Design view. Select Text, PlainText in the Palette and drag it to the editor:

Drop it just above the ‘Hello World!’ text.

Now we will constrain the element to the top and left. When you hover over the circles, you can see you can interact with them (image 1 below). Click the circle and drag it upwards. The element will be moved to the top. Now drag the element down (click-and-hold):

Do the same with the left side, and center the element:

Also align the ‘Hello World!’ text to the left side of the textField (drag its left-constraint circle to the left of the textField above it). Select the textField. Under Attributes, change its ID to “textField1”:

From the Palette, add a Button and constrain it to the textfield by clicking the small circle: do this for the left and top-constraints. Set it’s text to “Ok”.

Run the App and verify everything is positioned well: (if you do not have a Virtual Device yet, create one)

(Do not close the emulator)

Remove the “Hello World!” text from the TextView (it should be empty):

Assign the ID “textView” to the TextView:

Check if the button has the ID “button”. You might also notice some warnings like these:

You may ignore these for now, we will fix these at the end.

Add an eventlistener

Add an eventlistener for the Ok button:

Switch to MainActivity.java. You can also find it in the Project Structure under app, java, com.vanslooten.assignment1 (your package name might be different).

Add the code below to the onCreate() method:

Button buttonOk = findViewById(R.id.button);
 buttonOk.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
         System.out.println("Ok pressed");
     }
 });

When you do this, some text will turn red:

This is because you will have to import the class for “Button”. Click the red text “Button”, then press Alt+Enter and then select “Import Class” to fix the error (it will automatically add the import at the top of the code).

Inside the onClick() eventhandler, we need a reference to textField1 to be able to read it’s value (the text typed in by the user).
Switch back to the Design-view of content_main.xml and in the component tree right click the textField1 and select “Goto XML”. This will switch to the Text-view, and show the selected component’s XML code:

This shows the type of this element is ‘EditText’ (it’s class it EditText). To make a reference (a variable of this type) we can use:

EditText textField1 = findViewById(R.id.textField1);

Add the line above right after the System.out.println line inside the onClick() eventhandler.

In the same way, add a reference to the TextView yourself. Make sure it gets the name ‘textView’ (it starts with a lowercase ‘t’, because it is a variable name).

Add this line:

textView.setText( "Hello, " + textField1.getText() );

And test! (File > Save all; Run > Run ‘app’)

If you type your name and hit the Ok button, result should look like:

You can also review the code from the image above, in case you need it.

Things to fix:

Use hint instead of placeholder

When you test the App, you might notice that it is rather annoying that, when you start typing, you first have to remove the placeholder text ‘Name’.
Instead of having this text in the text-attribute of the textField, it is better to put it in the hint-attribute: In the Attributes of textField1, at text remove the value (attribute should be empty), then scroll down until hint and enter ‘Name’ there.
Another way to do this, is change the xml code: switch to the Text tab, find textField1, change android:text="Name" to android:hint="Name":

Use resources instead of hard-coded strings

You might encounter warnings about strings:

Your app will work fine, it is just a warning. But if you want to build larger apps and for instance support multiple languages, you should fix this. We show how to do this for the hint value for textField1:

Select textField1 and in the list of attributes scroll down to the hint value and make this value empty. Then click the small button ‘Pick a Resource’:

The dialog to define resources appears. In the upper right corner click “Add new resource”, then “New string Value”. Enter the Resource name and value and press Ok:

The value will now be @string/hint

Prevent errors

If nothing is typed, and the Ok button is pressed, a warning should be displayed, eg.: “Please enter your name, then press Ok”.

See the example use of ‘Snackbar’ in code above: fab.setOnClickListener…
Add this to the eventlistener:

if (textField1.getText().length()<1) {
      Snackbar.make(view, "Please enter your name, then press Ok", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}

Now move the code which displays the “Hello, ” message in the ‘else’ part of this if-statement. (Add the ‘else’ yourself).

Make the share button work

Find the code which adds an eventhandler to the Floating Action Button. In the eventhandler, remove the line with Snackbar.make... and add code to handle press of that button.

You can find plenty of examples of how to handle the share button. For instance this example shows how to send an e-mail with it. The code below can be used to accomplish this.

// get reference to textField1:
EditText textField1 = findViewById(R.id.textField1);

// send e-mail by using the 'Send to' Intent:
Intent email = new Intent(Intent.ACTION_SENDTO);
email.setType("message/rfc822");
email.setData(Uri.parse("mailto:"));
email.putExtra(Intent.EXTRA_SUBJECT, "my first app"); // subject of the email
email.putExtra(Intent.EXTRA_TEXT, "Hello, I just created an 'hello world' app to greet " + textField1.getText()+"\n\n"); // the body of the email
try {
    startActivity(Intent.createChooser(email, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
    Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}

Please note that in order for this to work, you must have a working & configured e-mail app on the device running this app.

Make use of Enter key possible

When you hit the Enter key on the keyboard while entering the name, the same eventhandler should be invoked. How to do this is explained here.

More information

Continue to the series of articles on Android App Development.

Or, learn more from these tutorials and free courses: