Event Listeners
View类里的event listener是一个带有回调方法的接口,当UI里的组建是被用户触发时,这些方法会被系统框架所调用
来自View.OnClickListener 它会被调用当点击这个Item(在触摸模式),或者当光标聚集在这个Item上时按下“确认”键 ,导航键,或者轨迹球。
onLongClick()
来自View.OnLongClickListener. 它会被调用当长按这个Item(在触摸模式),或者当光标聚集在这个Item上时长按 “确认”键 ,导航键,或者轨迹球。
onFocusChange()
来自View.OnFocusChangeListener 它会被调用当光标移到或离开这个Item,
onKey()
来自View.OnKeyListener..它会被调用,当光标移到这个Item,按下和释放一个按键的时候
onTouch()
来自View.OnTouchListener. 它会被调用 ,在这个Item的范围内点触的时候
onCreateContextMenu()
// Create an anonymous implementation of OnClickListener private OnClickListener mCorkyListener = new OnClickListener() { public void onClick(View v) { // do something when the button is clicked } }; protected void onCreate(Bundle savedValues) { ... // Capture our button from layout Button button = (Button)findViewById(R.id.corky); // Register the onClick listener with the implementation above button.setOnClickListener(mCorkyListener); ... }
}
下面这个列子我们会发现用Activity去实现OnClickListener接口,并作为它的一部分,会更方便,而不必去加载额外的类和对象
public class ExampleActivity extends Activity implements OnClickListener { protected void onCreate(Bundle savedValues) { ... Button button = (Button)findViewById(R.id.corky); button.setOnClickListener(this); } // Implement the OnClickListener callback public void onClick(View v) { // do something when the button is clicked } ... }
Event Handlers
-
- Called when a new key event occurs.onKeyDown(int, KeyEvent)
-
- Called when a key up event occurs.onKeyUp(int, KeyEvent)
-
- Called when a trackball motion event occurs.onTrackballEvent(MotionEvent)
-
- Called when a touch screen motion event occurs.onTouchEvent(MotionEvent)
-
- Called when the view gains or loses focus.onFocusChanged(boolean, int, Rect)
还有其他一些方法,这不属于View类,但可以直接影响到你处理事件的方式,所以在布局内管理更复杂的事件可以考虑到这些方法:
-
- This allows yourActivity.dispatchTouchEvent(MotionEvent)
Activity
to intercept all touch events before they are dispatched to the window. -
- This allows aViewGroup.onInterceptTouchEvent(MotionEvent)
ViewGroup
to watch events as they are dispatched to child Views. -
- Call this upon a parent View to indicate that it should not intercept touch events withViewParent.requestDisallowInterceptTouchEvent(boolean)
.onInterceptTouchEvent(MotionEvent)
Touch Mode
Handling Focus
<LinearLayout android:orientation="vertical" ... > <Button android:id="@+id/top" android:nextFocusUp="@+id/bottom" ... /> <Button android:id="@+id/bottom" android:nextFocusDown="@+id/top" ... /> </LinearLayout>
一般来说,在这个垂直布局,浏览的焦点会从第一个按钮开始,不会是从第二个或者其他的,现在topButtont已经通过nextFocusUp (反之亦然)确定了bottom.
总结:
- 对于UI控件事件的处理,需要设定相应的监听器,并实现相应的事件处理程序。这儿有两种实现方法:一是定义一个OnClickListener 类的实例,并使用setOnClickListener等绑定监听器;二是用Activity去实现OnClickListener接口,并作为它的一部分,这样会更方便,省去了加载额外的类和对象的时间。
- 对于支持触摸屏的手机,可以设定触摸模式的UI,可以使用isInTouchMode()来获得触摸模式的状态。
- UI处理的另一个重点是焦点的设定及其切换。焦点设置:通过setFocusable或者setFocusableInTouchMode设置可以接受焦点,通过isFocusable或isFocusableInTouchMode获取是否可以接受焦点;焦点切换:编写XML布局文件的nextFocusDown 等属性设置。
- 参考:http://developer.android.com/guide/topics/ui/ui-events.html