Beginning Android Studio 1. Buttons

In this tutorial we will create a simple button that will answer us with a message when we click on it. I will be using the IDE Android Studio, but if you prefer to use another IDE you shouldn't have any problem following this tutorial. The finished program will look like this:

     

Getting started

Let's begin by creating a new project. You can name it whatever you want, I will simply call my project "Button", with the package name tutorials.hallucind.com. Make sure you choose Empty Activity, like so:

 

Now your MainActivity.java and activity_main.xml (if you kept the default name) should be opened. Click on activity_main.xml. If it didn't start, you can find it in app/res/layout/layout_main.xml:

                             

 

If you didn't encounter any render errors you will see a screen with a text saying "Hello world!".

XML: Summoning the button

There are two ways to implement the button. You can do it programmatically, that is, type some code in xml and see the button appear. The other way is to do it by drag and drop.

1. Implement the button programmatically

If you're still in activity_main.xml, you can see two tabs in the bottom left area with the text Design and Text.

                                                                

 

Click on the Text tab to see the actual xml document.

<?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Remove the TextView and add this:

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />



In the first line we just wrote, we declared our Button. You may have noticed how your  IDE forced you to add the two second lines if you didn't copy pasted it. This is because you need to specify the buttons width and height. I chose to put wrap_content between the double quotes to give our button a nice size. When we feed it some text, it will make sure to cover the text smoothly. Another option is match_parent, which will make the button as big it can. You can also specify the width and height by pixels, use the dp (density-independent pixel) suffix in that case. Feel free to play around with it, click on the Design tab, bottom left corner, to see how it changes when you give it different values. I'm gonna stick with wrap_content.

Let's put some text on the button. Click right before "/>" and then hit Enter on your keyboard to make sure you're still in the Buttons territory. Everything that has to do with the button must be inside the <Button and /> tags. Then add the line:

android:text="do something awesome"

 

If you take a look at the button now, you will see that we successfully added text to it. The button is in a somewhat boring position right now, so let's move it. We add the following to move it to the middle:

app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"

 

Constraint is the type of layout we use here. There are other types of layouts to better fit other situations needs, but we don't need to think about that in this example. To be able to make it reachable by Java so we can make it do something awesome when we click on it we need to give it an id, so we add this line to the top:

android:id="@+id/button"

Here we give it the id "button". It doesn't really matter where you place the lines inside an element, I just like to have the id's at the top so I can find them quickly. The button layout is done ! Did you notice how similar our code is to the TextView in the beginning? In fact, we could have just changed the "TextView" to "Button" and we would be done, but since this is a tutorial and I want you to learn things that would be rather unpractical. The complete activity_main.xml:

<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="do something amazing"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>

2. Implement the button by drag and drop

In the Design tab, you have a palette with elements you can use. From there you can just drag and drop the button to the screen and you're done.

          

 

All you have to do after the drop is to check the id in the Text tab. Painful, right? Much better to do it programmatically, isn't it? Moving on.

Open up MainActivity.java. If you accidentally closed it or it never showed up, you find it in app/java/yourpackage/MainActivity.java.

                                         

 

Make sure it says Android in the very top there, select it if it does not.

It should look like this:

package com.hallucind.tutorials.button;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

The onCreate method is the first method that runs when you start the app, so inside this method would be the ideal place to connect the button. The line

setContentView(R.layout.activity_main);

tells the compiler that we want to use the layout activity_main.xml, and that's the place it should look for all the elements we want to manipulate. Under that line, add:

Button button = findViewById(R.id.button);

The Button-text will most likely become red, just click on it and then hit Alt + Enter on your keyboard to import the missing package. We declare a button and use the findViewById function to attach the button we want to manipulate. We give the function our buttons id as a parameter, R.id.button. R is for resources, it's looking in the resources for our id which has the name button. Compare this with the setContent(R.layout.activity_main); method. It's looking in the resources for the layout we want to use, which has the name activity_main.

We want our button to do something awesome when we click on it, therefore we tell it to listen to for a click:

    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

        }
    });

Put that line below Button button = findViewById(R.id.button);. Inside the method onClick iswhere you determine what should happen when you click on the button. In this example I'm goingmake a Toast:

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "Doing something awesome!",
                                Toast.LENGTH_LONG).show();
            }
        });

The Toast takes in three parameters, Context, String to show and the display time, in that order. Don't forget the .show(), else it won't show up.

That's it! Run your app, click the button and see something awesome happening.

                            

Enjoyed this article? Give the teacher an apple.

cookie

0

Author

authors profile photo

Articles with similar tags

Comments