Android ImageButton Example Code

In this tutorial, we are going to learn about ImageButton in android i.e. How to display an image on a button? As you click on the image button a toast message is displayed.
Submitted by Shamikh Faraz, on MAY 05, 2018

1) XML File: activity_main

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="com.example.faraz.imagebutton_example.MainActivity">

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/finger"
        tools:layout_editor_absoluteX="130dp"
        tools:layout_editor_absoluteY="155dp" />
</android.support.constraint.ConstraintLayout>

2) File: MainActivity.java

package com.example.faraz.imagebutton_example;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

    ImageButton imageButton;

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

        addListenerOnButton();

    }

    public void addListenerOnButton() {

        imageButton = (ImageButton) findViewById(R.id.imageButton1);

        imageButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Toast.makeText(MainActivity.this, "You Clicked Image Button!", Toast.LENGTH_LONG).show();

            }

        });

    }

}

Note: Remember image button size should be 100dp and 50dp. You can resize it, but should not be very large.

Output

After executing your code, you get an image. Actually this is not only an image, but a button containing an image. As you click on the image button a toast message is displayed as “You Clicked Image Button”.

Output - Android ImageButton Example Code 1
Output - Android ImageButton Example Code 2


Related Tutorials



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.