Beginning Android Studio 3. ImageButton (With Selector)

Introduction

Welcome to the third tutorial in the Beginning Android Studio series. In the last episode, you learned about textviews and inputs. This time we will go through the component ImageButton and see what we can do with it. Here's what we will be creating:

 

Getting started

We will need two images for this mission, one for the normal state, and one for the pressed state. I will be using these two images:

The left image will be used as the normal state, and the sad face will be used as the pressed state, given the names happyface.png respective sadface.png. Drop your images in app/res/drawable/. When you're done with that, right click on the drawable folder and select New -> Drawable Resource File and type in "clickbutton.xml" in the File Name field.

This file will control the states of our ImageButton that we will create soon:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/sadface" />
    <item android:drawable="@drawable/happyface" />
</selector>

 

If you examine the code, it's pretty self explanatory. The focus is on the two item lines. When the button is pressed, we want the sadface to show up, which is determined by android:state_pressed="true" and android:drawable="@drawable/sadface". @drawable/sadface is just the location to your image. The line below is the default state, when no other state is given, therefore we don't need to put any "android:state_somestate" in there.

That's it for our drawable folder, let's switch focus to activity_main.xml in the layout folder. Locate ImageButton in the Palette to the left, and drag it out to the screen. When you drop it, a window will pop up. Expand Project and choose the file we created, clickbutton, and press OK.

Notice the gray area around the button? I'm not a fan of that either. Good thing is that we can remove it! Get into Text mode (bottom left, click on the Text tab) so we can change the code. Inside your ImageButton here, add the line:

android:background="@null"

to tell Android that we don't want this element to have a background. And the gray area disappeared. Here's my ImageButton:

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@null"
        app:srcCompat="@drawable/clickbutton" />

 

If you looked at the video, I got something more planned for us today. When the button is clicked, there's a text popping up saying "ouch" because you beat the poor face when you click on it. I'm adding the TextView to our app:

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="103dp"
        android:gravity="center"
        android:textSize="30sp" />

 

How do I center the text horizontally? You may ask. Well, the line android:layout_width="match_parent" will make the text occupy the whole screen horizontally, And to make the text appear in the middle of the textfield, the line android:gravity="center" is added. Here's our full activity_main.xml file:

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

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@null"
        app:srcCompat="@drawable/clickbutton" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="103dp"
        android:gravity="center"
        android:textSize="30sp" />
</RelativeLayout>

 

Making it scream

Open up MainActivity.java, it's time to make our image respond on clicks. It's important to know however that the image is changed when we click on it already, our clickbutton.xml file made that happen. Try it for yourself!

Anyway, proceeding. In the global scope, add the variables:

    ImageButton btn;
    TextView txt;

And inside the onCreate() method, connect your variables with the actual components:

        txt = findViewById(R.id.textView);
        btn = findViewById(R.id.imageButton);

 

In the other tutorials we have learned about the setOnClickListener to make a button respond to a click. The disadvantage of this is that it only detects when you release the button. I want the text to say "Ouch!" when the image is pressed, and when the image is released I want the text to be cleared. This cannot be done with a simple click listener. setOnTouchListener to the rescure.

Add the code:

        btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return false;
            }
        });

The variable passed called motionEvent holds the gesture the user is performing. We can check if the user is performing a specific gesture easily. I prefer to use switch statements for this behavour, but if you like if statements more then use that, it doesn't really matter. We will check if motionEvent.getAction() is equal to MotionEvent.ACTION_DOWN or MotionEvent.ACTION_UP. If it's ACTION_DOWN, the button was pressed, and we set the text to "Ouch!". If it's ACTION_UP, we clear the text. Here's the final MainActivity.java:

package com.hallucind.tutorials.imagebutton;

import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    ImageButton btn;
    TextView txt;

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

        txt = findViewById(R.id.textView);
        btn = findViewById(R.id.imageButton);

        btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        txt.setText("Ouch!");
                        break;

                    case MotionEvent.ACTION_UP:
                        txt.setText("");
                        break;
                }
                return false;
            }
        });
    }
}

 

Enjoyed this article? Give the teacher an apple.

cookie

0

Author

authors profile photo

Articles with similar tags

Comments