Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Android ImageButton example
- 1. Add Image to Resources
- Put image “android_button.png” into “res/drawable-?dpi” folder. So that Android know where to find your image.
- 2. Add ImageButton
- Open “res/layout/main.xml” file, add a “ImageButton” tag, and defined the background image via “android:src“.
- File : res/layout/main.xml
- <?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" >
- <ImageButton
- android:id="@+id/imageButton1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/android_button" />
- </LinearLayout>
- 3. Code Code
- Here’s the code, add a click listener on image button.
- File : MyAndroidAppActivity.java
- package com.mkyong.android;
- 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 MyAndroidAppActivity extends Activity {
- ImageButton imageButton;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- addListenerOnButton();
- }
- public void addListenerOnButton() {
- imageButton = (ImageButton) findViewById(R.id.imageButton1);
- imageButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- Toast.makeText(MyAndroidAppActivity.this,
- "ImageButton is clicked!", Toast.LENGTH_SHORT).show();
- }
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement