Advertisement
atiqxp

Android ImageButton example

Apr 29th, 2014
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
XML 1.76 KB | None | 0 0
  1. Android ImageButton example
  2.  
  3. 1. Add Image to Resources
  4.  
  5. Put image “android_button.png” into “res/drawable-?dpi” folder. So that Android know where to find your image.
  6.  
  7. 2. Add ImageButton
  8.  
  9. Open “res/layout/main.xml” file, add a “ImageButton” tag, and defined the background image via “android:src“.
  10.  
  11. File : res/layout/main.xml
  12.  
  13. <?xml version="1.0" encoding="utf-8"?>
  14. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  15.    android:layout_width="fill_parent"
  16.    android:layout_height="fill_parent"
  17.    android:orientation="vertical" >
  18.  
  19.     <ImageButton
  20.        android:id="@+id/imageButton1"
  21.        android:layout_width="wrap_content"
  22.        android:layout_height="wrap_content"
  23.        android:src="@drawable/android_button" />
  24.  
  25. </LinearLayout>
  26.  
  27.  
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
  34. 3. Code Code
  35.  
  36. Here’s the code, add a click listener on image button.
  37.  
  38.  
  39.  
  40.  
  41. File : MyAndroidAppActivity.java
  42.  
  43.  
  44.  
  45. package com.mkyong.android;
  46.  
  47. import android.app.Activity;
  48. import android.os.Bundle;
  49. import android.widget.ImageButton;
  50. import android.widget.Toast;
  51. import android.view.View;
  52. import android.view.View.OnClickListener;
  53.  
  54. public class MyAndroidAppActivity extends Activity {
  55.  
  56.     ImageButton imageButton;
  57.  
  58.     @Override
  59.     public void onCreate(Bundle savedInstanceState) {
  60.         super.onCreate(savedInstanceState);
  61.         setContentView(R.layout.main);
  62.  
  63.         addListenerOnButton();
  64.  
  65.     }
  66.  
  67.     public void addListenerOnButton() {
  68.  
  69.         imageButton = (ImageButton) findViewById(R.id.imageButton1);
  70.  
  71.         imageButton.setOnClickListener(new OnClickListener() {
  72.  
  73.             @Override
  74.             public void onClick(View arg0) {
  75.  
  76.                Toast.makeText(MyAndroidAppActivity.this,
  77.                 "ImageButton is clicked!", Toast.LENGTH_SHORT).show();
  78.  
  79.             }
  80.  
  81.         });
  82.  
  83.     }
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement