2011年10月11日火曜日

Button

Buttonは、ボタンを押した時に何か処理を実行するために使います。

使い方は、ボタンがクリックされたときにイベントを受け付けるように、リスナーを設定します。
Button btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // 実行する処理
    }
});
まずfindViewById()メソッドを使って、リソースIDからボタンのインスタンスを取得します。
次にそのボタンに対して、setOnClickListener()メソッドを使ってリスナーを設定し、onClick()メソッドを記述します。


ボタンクリックでメッセージを表示

ボタンをクリックするとメッセージを表示するサンプルプログラムです。メッセージの表示にはToastを使います。Toastは次の記事で説明する予定です。

Androidプロジェクトの設定
プロジェクト名:ButtonTest1
ビルドターゲット:Android 2.1-update1
アプリケーション名:ButtonTest1
パッケージ名:jp.co.triware.samples.ButtonTest1
アクティビティーの作成:ButtonTest1
最小SDKバージョン:7
ButtonTest1.java
package jp.co.triware.samples.ButtonTest1;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class ButtonTest1 extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // "SHORT"ボタン
        Button btnShort = (Button)findViewById(R.id.short_btn);
        btnShort.setOnClickListener(new View.OnClickListener() {
            // @Override // JDK1.5ではビルドエラー
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "SHORTボタンが押されました。", Toast.LENGTH_SHORT).show();
            }
        });

        // "LONG"ボタン
        Button btnLong = (Button)findViewById(R.id.long_btn);
        btnLong.setOnClickListener(new View.OnClickListener() {
            // @Override // JDK1.5ではビルドエラー
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "LONGボタンが押されました。", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
        android:id="@+id/short_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SHORT"
        />
    <Button
        android:id="@+id/long_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="LONG"
        />
</LinearLayout>

実行結果
「SHORT」ボタンをクリックすると2秒間、「LONG」ボタンをクリックすると4秒間、メッセージを表示します。

0 件のコメント:

コメントを投稿