今回はボタンを配置しボタンがクリック動作を取得します
ボタンがクリックされると
・Clickイベント・Touchイベント・LongClickイベントが以下の順に発生します
(1) OnTouchイベント (MotionEvent.ACTION_DOWN)
(2) OnLongClickイベント
(3) OnTouchイベント (MotionEvent.ACTION_UP)
(4) OnClickイベント
※2番目のOnLongClickイベントは長押の場合です
Clickイベントを取得する
まずはレイアウトにボタンを配置します
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" > <Button android:id="@+id/button_test" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /> </LinearLayout>idにはbutton_testというのを割り当てています
次にActivity(TestActivity)の設定です
package blog.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class TestActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //id button_testをbに当てはめている Button b = (Button)findViewById(R.id.button_test); //bが押された時の動作 b.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showMessage("ボタンが押されました"); } }); } /**トースト設定**/ protected void showMessage(String msg){ Toast.makeText( this, msg, Toast.LENGTH_LONG).show(); } }
ボタンを押すとトーストに“ボタンが押されました”とでます

スポンサードリンク
【ウィジェット ボタンの最新記事】