`
阅读更多

    1、有如下事件:

     setOnClickListener ,

   setOnLongClickListener

    setOnTouchListener

   setOnFocusChangeListener

   setOnKeyListener

 

2、形式:

   已知的XML文件

   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:id="@+id/layout01">"

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

 button1.setOnLongClickListener(new View.OnLongClickListener() {
  
  @Override
  public boolean onLongClick(View v) {
   // TODO Auto-generated method stub
   System.out.println("长按");
   return false;
  }
 });
     button.setOnClickListener(new View.OnClickListener() {
  
  @Override
  public void onClick(View v) {
   // TODO Auto-generated method stub
   System.out.println("单击");
  }
 });

长按一下button1后并且释放

输出:长按

         单击

得出在长按了组件后,两个事件都执行了。为了只执行长按的事件,需要在setOnLongClickListener的返回值里修改返回值。它决定了对组件长按后是否还加入一个短按。设为TRUE,则表明不加入短按;设为FALSE,则表明加入短按。

官方解释里:true和false在其中起着标志事件是否被消耗,如果消耗了就不再传递给其他控件了。如果没有消耗则还会传递给其他控件,触发其他控件的事件处理函数

 viewGroup=(ViewGroup)findViewById(R.id.layout01);

viewGroup.setOnTouchListener(new View.OnTouchListener() {
  
  @Override
  public boolean onTouch(View v, MotionEvent event) {
   // TODO Auto-generated method stub
   int actionType=event.getAction();
   if(actionType==MotionEvent.ACTION_DOWN){
    System.out.println("anxia");
   }else if(actionType==MotionEvent.ACTION_MOVE){
    button.setX(event.getX());
    button.setY(event.getY());
    System.out.println("yidong");

   }else if(actionType==MotionEvent.ACTION_UP){
    System.out.println("songkai");

   }


   return true;
  }
 });

 这个事件的参数很特别,加了一个MotionEvent。要注意,事件是由事件元组成的,它们是MotionEvent类的常量。如ACTION_DOWN,ACTION_MOVE等等。

不同的操作,打印不同的话。

 

最后还有setOnKeyClickListener

button.setOnKeyListener(new View.OnKeyListener() {
  
  @Override
  public boolean onKey(View v, int keyCode, KeyEvent event) {
   // TODO Auto-generated method stub
  //keyCode是一个整型,键盘上通过不同的按键对应着不同的值,我们可以通过这种思想,实现用键盘来操控组件。
  //a:29
   System.out.println(keyCode);
   if(29==keyCode){
    button.setX(button.getX()-20);
   }else
   if(32==keyCode){
    button.setX(button.getX()+20);
   }else
   if(51==keyCode){
    button.setY(button.getY()-20);
   }else
   if(47==keyCode){
    button.setY(button.getY()+20);
   }
   return false;
  }
 });

实现了用WASD,来控制,组件的移动。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics