一):匿名内部类
Button btnConfirm = (Button) findViewById(R.id.btnConfirm);
btnConfirm.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Hello world", 0).show();
}
二):内部类
class ConfirmOnClickListener implements OnClickListener{
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Hello world", 0).show();
}
}
btnConfirm.setOnClickListener(new ConfirmOnClickListener());
三):Activity类实现OnclickListener接口
public class MainActivity extends Activity implements OnclickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnConfirm = (Button) findViewById(R.id.btnConfirm);
btnConfirm.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Hello World", 0).show();
}
}
当多个按钮的时候, 可以用switch来确定点击的按钮
public class MainActivity extends Activity implements OnclickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnConfirm = (Button) findViewById(R.id.btnConfirm);
Button btnCancel = (Button) findViewById(R.id.btnConfirm);
btnConfirm.setOnClickListener(this);
btnCancel.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnConfirm:
Toast.makeText(this, "点击了确定按钮", 0).show();
break;
case R.id.btnCancel:
Toast.makeText(this, "点击了取消按钮", 0).show();
break;
default:
break;
}
}
}
四):控件onClick属性设置单击事件
<Button
android:id="@+id/btnConfirm"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="confirmClick"
android:text="@string/CONFIRM"/>
MainAcvitity类添加:
public void confirmClick(View v){
Toast.makeText(this, "点击了确定按钮", 0).show();
}