本日はボタン処理を解説します。

やっとアプリ開発っぽくなってきました。
先に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:gravity="center"
android:orientation="vertical" >

<Button android:text="TEST1"
android:id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>


android:idって指定がありますね。
javaからオブジェクト(今回ならボタン)を取得するのに必要なので、
必ず指定します。
(アプリ内でユニーク)

次にjavaのコード(ボタンの取得~設定)です。
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_toast);

Button btn = (Button)findViewById(R.id.test);
btn.setOnClickListener(new BtnExecute());
}


Button btn = (Button)findViewById(R.id.test);
上記のfindViewByIdでボタンを取得しています。
戻り値がObject型なので今回ならButtonにキャストしてあげます。
(同じ方法でButton以外の画面要素を何でも取得できます。)

btn.setOnClickListener(new BtnExecute());
見た感じで分かりそうですが、ボタン押下時に実行する処理を指定します。

ボタン押下処理クラスは以下

public class BtnExecute implements View.OnClickListener
{
@Override
public void onClick(View v)
{
Toast.makeText(v.getContext(), "BUTTON", Toast.LENGTH_LONG).show();
}
}


重要なのはView.OnClickListenerをimplementsしてるところです。
要は View.OnClickListenerを使っているクラスなら誰でもいい訳です。
Activityにimplementsを付けてあげてもいいですし、
フロントコントローラーちっくに全ボタン共通の入口を用意してもいいです。

View#getContextの存在を知らずに、コンストラクタにContextを渡してクラス内に保持などは止めましょう
(必要なら有りです。)

動作イメージです。
まずは押下前(昔は押下を"おした"の変換ミスだと思ってました。)


ボタン押下


ここまでの情報+αでジャンケンゲームくらい出来そうですね。