開発者ドキュメント

Android ImageButtonの例

Androidでは、「http://developer.android.com/reference/android/widget/ImageButton.html[android.widget.ImageButton」」を使用して、カスタマイズされた背景画像を持つ通常の「ボタン」を表示できます。

このチュートリアルでは、 ”

android__button.png

“という名前の背景イメージを持つボタンを表示する方法を示します。ユーザーがそれをクリックすると、短いメッセージが表示されます。それと同じくらい簡単です。


P.SこのプロジェクトはEclipse 3.7で開発され、Android 2.3.3.

でテストされています

1.画像をリソースに追加する

イメージ ”

android

button.png


“を “res/drawable-?dpi__”フォルダに置きます。あなたのイメージを見つける場所をAndroidが知るようにします。

2. ImageButtonを追加する



res/layout/main.xml

“ファイルを開き、 “ImageButton”タグを追加し、 “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.コードコード

ここにコードがあり、画像ボタンにクリックリスナーを追加します。


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();

            }

        });

    }

}

4.デモ

アプリケーションを実行します。

{空} 1。結果、カスタマイズされた背景画像を持つボタン。



{空} 2。ボタンをクリックすると、短いメッセージが表示されます。



ソースコードをダウンロードする

ダウンロードする –

Android-ImageButton-Example.zip

(28 KB)

参考文献

ImageButtonの例]

リンク://タグ/アンドロイド/[アンドロイド]リンク://タグ/イメージボタン/[イメージボタン]

モバイルバージョンを終了