方式1 采用匿名内部类方法
button1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0) {
System.out.println("button1 clicked");
}
});
方式2 采用activity实现OnClickListener接口
public class TaskActivity extends Activity implements ClickListener
{
public void onClick(View arg0)
{
if(arg0==button1)
System.out.println("button1 clicked");
else if (arg0==button2)
System.out.println("button2 clicked");
...
}
}
方式3 修改XML android:onClick 属性
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/self_destruct"
android:onClick="selfDestruct" />
Now, when a user clicks the button, the Android system calls the activity's selfDestruct(View) method. In order for this to work, the method must be public and accept a View as its only parameter. For example:
public void selfDestruct(View arg0) {
System.out.println("button1 clicked");
}