一.android事件处理的两种途径
1:基于监听
2:基于回调
某些特定的事件无法用回调的方法。
二.基于监听的方法
比较常用的方法
1:内部类
使用内部类就是在类的内部定义一个实现了某个onxxxlistener接口的类,然后将这个内部类的实例注册给事件源。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到事件源
Button btn = (Button) findViewById(R.id.btn);
//绑定事件监听器
btn.setOnClickListener(new MybtnOnclickListener());
}
//使用内部类
public class MybtnOnclickListener implements OnClickListener {
@Override
public void onClick(View v) {
// do something you want to do
}
}
}
2:使用匿名内部类
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到事件源
Button btn = (Button) findViewById(R.id.btn);
//绑定事件监听器
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//do something you want to do
}
});
}
}
3:使用XML绑定
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="MyButtonCilcked"/> 此处绑定
</RelativeLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void MyButtonCilcked(View v)
{
//do something you want to do
}
}
三:基于回调的方法
不用事件监听器,事件源本身来处理事件,多用于自定义的view,重写了父类的onxxxlistener方法。
常用回调方法有:
onKeyDown //按键按下
onKeyLongPress //长按键
onKeyShortcut //键盘快捷键按下
onKeyUp //松开按键
onTouchEvent //触摸屏事件
onTrackballEvent //轨迹球事件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="MyButtonCilcked"/>
<chao.he.eventtest.MyButton //用我们自定义的view
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
public class MyButton extends Button {
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
//重写父类的onTouchEvent方法
@Override
public boolean onTouchEvent(MotionEvent event) {
//do something you want to do
return true;
}
}
基于回调方法的事件传播取决于回调事件的返回值,如果返回false则事件继续向外传播,如返回true则事件停止。
一般先执行监听器绑定的事件,然后执行在view中定义的回调事件,最后执行Activity中的回调事件。