OnClickListener
ボタン等、部品にクリックイベントを設定する為に使用します。
設定する方法はいくつかありますが、implementsに設定する方法をオススメします。
かつswitchでボタンidを判定する方法が自分は好きです。
かつswitchでボタンidを判定する方法が自分は好きです。
![]() |
| Button配置 |
![]() |
| Clickイベント |
MainAcitivity.java
public class MainActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ボタン部品取得
Button _btn1 = (Button)findViewById(R.id.button1);
Button _btn2 = (Button)findViewById(R.id.button2);
Button _btn3 = (Button)findViewById(R.id.button3);
//ボタンをクリックリスナーへ登録
_btn1.setOnClickListener(this);
_btn2.setOnClickListener(this);
_btn3.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
// TODO 自動生成されたメソッド・スタブ
//オススメはswitchを使用
switch(arg0.getId()){
case R.id.button1:
//【おはようボタン】のイベントを記載
Toast.makeText(this, "おはよう!", Toast.LENGTH_SHORT).show();
break;
case R.id.button2:
//【こんにちわボタン】のイベントを記載
Toast.makeText(this, "こんにちわ!", Toast.LENGTH_SHORT).show();
break;
case R.id.button3:
//【こんばんわボタン】のイベントを記載
Toast.makeText(this, "こんばんわ!", Toast.LENGTH_SHORT).show();
break;
}
}
}
res/layout/activity_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" android:gravity="center" > <Button android:text="おはよう" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"> </Button> <Button android:text="こんにちわ" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"> </Button> <Button android:text="こんばんわ" android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content"> </Button> </LinearLayout>


0 件のコメント:
コメントを投稿