Android provides an image button via android.widget.ImageButton
.
Using an image button is similar to using the basic button.
<ImageButton android:id="@+id/imageButton2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="myClickHandler" android:src="@drawable/icon" />
Java code to set image to an ImageButton
.
ImageButton imageButton2 = (ImageButton)this.findViewById(R.id.imageButton2); imageButton2.setImageResource(R.drawable.icon);
The image file for the button must exist under /res/drawable
.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > // w w w . ja va 2 s.c om <ImageButton android:id="@+id/imageButton2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="myClickHandler" android:src="@drawable/ic_launcher" /> </LinearLayout>
Java code
package com.java2s.app; //from ww w.ja v a 2 s .c om import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }