按钮事件点击的实现
1.在avtivity中给按钮绑定点击事件的侦听:
Button bt1 = (Button) findViewById(R.id.bt1);
bt1.setOnClickListener(new OnClickListener() {@Override public void onClick(View v) { System.out.println("第一个按钮被点击了"); } }); Button bt2 = (Button) findViewById(R.id.bt2); bt2.setOnClickListener(this);
- 2.在xml布局文件中给按钮增加onclick属性,在activity中写onclick的方法调用。
- xml:
“<Button
android:id="@+id/wangzhe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点我上王者"
android:onClick="getScore"
/>
<Button
android:id="@+id/diamond"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点我上钻"
android:onClick="getScore"
/>
<Button
android:id="@+id/master"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点我上大师"
android:onClick="getScore"
/>
“ - activity:
- xml:
public void getScore(View v){
//通过对view对象的判断,就可以知道用户点击的到底是哪一个按钮
//拿到按钮的id
int id = v.getId();
switch (id) {
case R.id.wangzhe:
System.out.println("下辈子吧");
break;
case R.id.diamond:
System.out.println("凑合凑合");
break;
case R.id.master:
System.out.println("想想就好");
break;
}
}