ボタンのイベントについては前回を参照してください
ボタンがクリックされるイベントを取得
まずはres/layout/main.xml
にボタンを2つ配置します
<?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" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2" />
</LinearLayout>
それぞれidをbutton1、button2としています
次に次にActivity(TestActivity)の設定です
package blog.test;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class TestActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/**それぞれのidを設定**/
Button button1=(Button)findViewById(R.id.button1);
Button button2=(Button)findViewById(R.id.button2);
/**ボタンが押されたらonClickが動作するよう設定**/
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
/**ボタンが押された時の処理**/
public void onClick(View v){
switch(v.getId()){
case R.id.button1:
showMessage("button1 が押されました。");
break;
case R.id.button2:
showMessage("button2 が押されました。");
break;
}
}
/**トースト設定**/
protected void showMessage(String msg){
Toast.makeText(
this,
msg, Toast.LENGTH_LONG).show();
}
}
10行目のimplements OnClickListenerとあります
自分自身のクラスに「OnClickListener」インタフェースを実装する
といいます
これはonCreateで設定したものにOnClickListenerが使えるよ〜
ということを表します
button1を押すと・・・
button2を押すと・・・
スポンサードリンク
【ウィジェット ボタンの最新記事】

