This example will tell you how. Listen And Response Button Click Event. You have two methods to response button click event as below. Create a View.OnClickListener object and assign the object to the button instance use setOnClickListener method. Button3.setOnClickListener (new View.OnClickListener @Override public void onClick (View view). Android Studio is used to create the sample. The screen orientation attribute is provided by the activity element in the Android Manifest.Xml file. The orientations provided by the activity are Portrait, Landscape, Sensor, Unspecified and so on.
An ImageButton UI control falls under the AbsoluteLayout which makes it possible for the ImageButton to specify the accurate location of its children. This UI control usually appears as a button with an icon or image rather than a text on it. To use this UI control during the runtime of the application, a user can either click or press it.
Also Read: Android Spinner
Various ImageButton Attributes
The below-provided tables contain major attributes associated with the ImageButton control. In case, you want to see the complete list of the ImageButton attributes then check out the official Android document. The document will also introduce you to the methods which are capable of changing the values of Imagebutton attributes even at the runtime.
[post_middile_section_ad]
The following list of ImageButton attributes is inherited from the android.widget.ImageView class.
S. No. | Attribute | Description |
1 | android:src | * This attribute accepts a drawable value which is then set as the content of the ImageView. |
2 | android:baseline | * The value of this attribute depicts the offset of the baseline used. This is applicable to a particular ImageView. |
3 | android:baselineAlignBottom | * The value for this attribute can either be true or false. * If you want to align the baseline with the bottom edge then set the value as true. |
4 | android:cropToPadding | * This attribute accepts either true or false as its value. * If it is set as true then the provided image will be cropped to fit within the mentioned padding. |
5 | android:adjustViewBounds | * The value of this attribute can either be accepted as true or false. * If this value is set to true then the ImageView will adjust its boundaries to aspect ration of the drawable provided. |
The following list of ImageButton attributes is inherited from the android.view.View class.
S. No. | Attribute | Description |
1 | android:id | * The value passed to this attribute will be considered as the identifier name of the view. |
2 | android:background | * This attribute accepts a drawable value which is then be set as a background for the view. |
3 | android:visibility | * The value of this attribute decides the visibility of the view on the application. |
4 | android:contentDescription | * This value accepts textual content which briefly explains the content carried by the view. |
5 | android:onClick | * This is a method which gets invoked when the view is clicked. |
[post_middile_section_ad]
To understand the use of above-mentioned attributes, take a look at the below-given example. It will introduce you to a step-to-step guide for the creation of an Android application with the help of Linear layout and ImageButton control.
Step 1: Start with opening the Android Studio IDE. In here, create an app under the name of myapplication. Store it within the com.example.myapplication. For the better understanding of this step, you can refer to the Hello World Example chapter.
Step 2: It’s time to add a click event to your application. For this, you need to open the MainActivity.java file. Go to src/ directory to find this file. Besides your entered code, the file will also be containing the pre-defined fundamental lifecycle callback methods.
package com.example.myapplication;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity
{
ImageButton imgButton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgButton =(ImageButton)findViewById(R.id.imageButton);
imgButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(),”You download is
resumed”,Toast.LENGTH_LONG).show();
}
});
}
}
[post_middile_section_ad]
Step 3: Include the following section of code in the activity_main.xml file. To locate this file, you can trace the res/layout/ directory. In here, you need to add the required Android UI control.
<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent”
android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
android:paddingBottom=”@dimen/activity_vertical_margin”
tools:context=”.MainActivity”>
<TextView android:text=”W3School”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:textSize=”30dp”
android:layout_alignParentTop=”true”
android:layout_alignRight=”@+id/imageButton”
android:layout_alignEnd=”@+id/imageButton” />
<ImageButton
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/imageButton”
android:layout_centerVertical=”true”
android:layout_centerHorizontal=”true”
android:src=”@drawable/abc”/>
</RelativeLayout>
Step 4: In the strings.xml file, you will get the definitions of the new string constants. You can find this file under the res/values/ path. Also, you don’t need to define these constants manually as the Android Studio takes care of it on its own.
<?xml version=”1.0″ encoding=”utf-8″?>
<resources>
<string name=”app_name”>myapplication</string>
</resources>
[post_middile_section_ad]
Step 5: Make sure you leave the code of the AndroidManifest.xml file as it is. The default content of the file is given below.
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.example.myapplication” >
<application
android:allowBackup=”true”
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name”
android:theme=”@style/AppTheme” >
<activity
android:name=”com.example.myapplication.MainActivity”
android:label=”@string/app_name” >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>
</manifest>
Step 6: Just run your myapplication on Android Studio IDE. For that, open any of the project’s activity files and click on the Run button. The Studio will install the app on your AVD (which has been already created during the environment setup) and then initiate the running process of your application. If the setup and the application run successfully, you will be displayed with a final output on the Emulator window.
On the screen, you will be displayed with an ImageButton and once you click on it, you will see a toast message on the screen.
In this tutorial a background is set on an ImageButton
to change its appearance. The article also shows how the ImageButton's appearance can be easily changed without the need to edit the image assigned to the button. This is done by changing the background for the ImageButton with a shape drawable.
(This Android ImageButton background tutorial assumes that Android Studio is installed, a basic App can be created and run, and the code in this article can be correctly copied into Android Studio. The example code can be changed to meet your own requirements.)
Prepare the App and the Images for the ImageButton
For this ImageButton tutorial a new project is created in Android Studio, here called ImageButton. An Empty Activity was used and all other settings left as default. On the app's screen, activity_main.xml, the TextView
showing Hello World! is deleted.
A graphic is required for use with the ImageButton. Here a couple of buttons will be used one to show a red cross and another a green tick. Using images from the Open Clip Art Library, a good source of free graphics, or use your own.
(To see how images from the Open Clip Art Libray can be converted into PNGs see the article Android Launcher Icons Using Inkscape or Free Android Icons Using OpenClipArt.org and Paint.NET.)
The images are also on the free Android Graphic Resources page. Use the greentick.zip and redcross.zip files, unzip them into the project, adding the contents to the project's res folder.
Add the ImageButtons to the App
With the activity_main.xml layout file open drag and drop an ImageButton from the Images on the Palette. A Resource Chooser dialog will open. Select the greentick drawable. (If the ConstraintLayout
is used add the required constraints.)
Do the same for the red tick, dragging and dropping an ImageButton on to the screen and selecting the redtick drawable graphic. With the graphics set for the two ImageButtons they are ready to be used by adding code to handle the onClick event, see Different Ways to Code Android Event Listeners.
Define the Background Shape Drawable
To improve the buttons appearance the background attribute for the ImageButton can be set. This is more flexible than modifying the image used by the button itself. The background attribute supports images but it also supports shapes defined in XML. The XML files are also drawables, so sit in the res/drawable folder. Unlike images it is not necessary to produce a version for all screen densities. To add a shape drawable background for the ImageButtons begin by creating a new shape XML file.
With app highlighted in the Project select New from the context menu (normally right-click) or from the main File menu. Select Android resource file, use button_background.xml for the File name, Drawable for the Resource type and shape as the Root element then press OK.
By setting appropriate gradient, padding and corners elements on a shape, and assigning it to the background attribute for the buttons, they are given a rounded button appearance. Edit the background_button.xml to have the following code:
Set the ImageButton Background Attribute
Use the Properties list for the ImageButton to set the Background property to @drawable/button_background (it can be selected using the ellipsis). The code for the activity_main.xml layout file should look something like this:
Here is the ImageButtons with a shape drawable:
Try different shape elements to see the effect on the ImageButton appearance. See the Android documentation on the Shape Drawable. The following shows some of the possible variations achieved, by setting the android:shape attribute on the shape root element, changing the color and its transparency, removing the padding element etc.
Android Button Image Text
Variations on Button Background
android:shape='oval'
on shape element
No padding element
Transparency of colors reduced (from B0 to 50)
Color changed (startColor='#B0FFE97F', endColor='#B0FFD800')
<solid android:color='#0094FF'/>
instead of gradient and no transparency set
Larger corners radius of 18dp
<stroke android:width='5dp' android:color='#7F0000'/>
Example of a dashed outline for the stroke:
Acknowledgements
The Green Tick and Red Cross are from openclipart.org.
Android Studio Image Button Onclick
See Also
Android Studio Image Button Examples
- For a full list of all the articles in Tek Eye see the full site Index.