在android开发中,经常会进行事件的绑定,来进行用户交互,今天小结一下android中事件绑定常用的几种方法
Android中按钮绑定事件的几种方法
在xml中注册 onclick方法
① xml文件中1
2
3
4
5
6
7 <Button
android:id="@+id/startBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startClick"
android:text="开始按钮"
/>
② java 代码中
public void startClick(View view){
Toast.makeText(getApplicationContext(),"在xml文件中绑定的方法",0).show();
}
③ 在xml中的onclick方法名应该与 java代码中的 方法名一致
在类中实现 View.OnClickListener接口
① xml文件:
<Button
android:id="@+id/startBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始按钮"
/>
② java代码
public class myListener implements OnClickListener{
//在初始化方法(如 onCreate())中添加
mbtn.setOnClickListener(this);
public void onClick(View view){
//具体实现的方法
}
}
使用内部类来监听事件的响应
① xml文件
<Button
android:id="@+id/startBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始按钮"
/>
② java 代码
public class myListener extends Activity{
//在初始化方法(如 onCreate 中添加)
mbtn.setOnClickListener(new mclicklistener());
//
private class mclicklistener implements OnClickListener{
public void onClick(View view){
//具体的点击实现响应方法
}
}
}
使用匿名内部类来监听事件的响应
① xml 文件
<Button
android:id="@+id/startBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始按钮"
/>
② java 代码
public class myListener extends Activity{
mbtn.setOnClickListener(new OnClickListener(){
public void onClick(View view){
//具体的点击实现响应方法
}
})
}
小结
上述就是Android中 几种常用的事件绑定的方法,在项目中,可根据实际情况选择绑定方法!