[安卓开发基础] 9 事件处理

<Android从入门到精通 项目案例版 第9章>

9.1事件处理种类:

事件处理过程:事件源,事件事件监听器

 

基于监听:setOnClickListener   按键 监听

 

基于回调的事件处理,重写方法:

public class IntentActivity extends AppCompatActivity {
     Button  
btn_start;
   
//鼠标右键----Generate---Overate Method----nTouchEvent  
     //  nTouchEvent  触摸 屏幕
    //  onKeyDown  onKeyUp    单击物理按钮
   
@Override
   
public boolean onTouchEvent(MotionEvent event) {
        Toast.makeText(IntentActivity.
this,"触摸",Toast.LENGTH_SHORT).show();
        return super
.onTouchEvent(event);


   
}

   
@Override
   
public boolean onKeyDown(int keyCode, KeyEvent event) {
        Toast.makeText(IntentActivity.
this,"按下",Toast.LENGTH_SHORT).show();
        return super
.onKeyDown(keyCode, event);
   
}

   
@Override
   
public boolean onKeyUp(int keyCode, KeyEvent event) {
        Toast.makeText(IntentActivity.
this,"抬起",Toast.LENGTH_SHORT).show();
        return super
.onKeyUp(keyCode, event);
   
}

实例:按按键连续按两次 超过两秒 Toast提示 “再按一次退出程序”按 返回键 提示:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
   
if(keyCode==KeyEvent.KEYCODE_BACK){
       
if((System.currentTimeMillis()-exitTime)>2000){
            Toast.makeText(IntentActivity.
this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
           
exitTime=System.currentTimeMillis();
       
}else{
            finish()
;
       
}
      
return  true;
   
}
   
return super.onKeyDown(keyCode, event);
}

触摸屏事件处理

 单击事件:

长按事件:长按两秒会调用

例如:长按按键

btn_start.setOnLongClickListener(new View.OnLongClickListener() {
   
@Override
   
public boolean onLongClick(View view) {

        Toast.makeText(IntentActivity.
this,"长按",Toast.LENGTH_SHORT).show();

        return false;
   
}
})
;

 

代码:

btn_start.setOnLongClickListener(new View.OnLongClickListener() {
       
@Override
       
public boolean onLongClick(View view) {

          
// Toast.makeText(IntentActivity.this,"长按",Toast.LENGTH_SHORT).show();
          
registerForContextMenu(view);//注册菜单
          
openContextMenu(view);//打开菜单

           
return false;
       
}
    })
;

}
//添加菜单
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
   
super.onCreateContextMenu(menu, v, menuInfo);
   
menu.add("收藏");
   
menu.add("删除");
}
//添加获取菜单
@Override
public boolean onContextItemSelected(MenuItem item) {


    Toast.makeText(IntentActivity.
this,"选择了"+item,Toast.LENGTH_SHORT).show();
    return super
.onContextItemSelected(item);
}

触摸事件:

快捷键,alt+回车 显示构造函数

实例代码:

创建  HatView类 继承View,Paint paint类  new创建对象 不能写在  OnDraw 方法里面,因为 onDraw 方法会重复调用否则会出现如下问题:

相关问题链接:https://blog.csdn.net/bzb123321/article/details/81298014?utm_source=blogxgwz1

>警告提示
Avoid object allocations during draw/layout operations (preallocate and reuse instead) less... (Ctrl+F1) 
You should avoid allocating objects during a drawing or layout operation. These are called frequently, so a smooth UI can be interrupted by garbage collection pauses caused by the object allocations.  The way this is generally handled is to allocate the needed objects up front and to reuse them for each drawing operation.  Some methods allocate memory on your behalf (such as Bitmap.create), and these should be handled in the same way.

> 提示 已经很清楚 就是 避免在实例化操作(提前分配并在draw和layout的时候 直接使用)

实例化操作会阻碍 垃圾回收机制 ,使 界面卡顿。
--------------------- 
作者:打码人bzb 
来源:CSDN 
原文:https://blog.csdn.net/bzb123321/article/details/81298014 
版权声明:本文为博主原创文章,转载请附上博文链接!

-------------------------

package com.event.Touch;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;

import com.zengjx.androidbaseproject.R;

/**
 * Created by zengjx on 2018/12/20.
 */

public class HatView   extends View{
    public     float bitmapX;
    public     float  bitmapY;//帽子显示的坐标
    Paint paint = new Paint(); //创建Paint对象
    Bitmap   bitmap;
    Context mcontext;
    public HatView(Context context) {
        super(context);
        mcontext=context;
        bitmapX=65;
        bitmapY=0;
        bitmap  = BitmapFactory.decodeResource(this.getResources(),R.drawable.hat);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

     //   Paint paint2= new Paint(); //创建Paint对象
       paint.setDither(true);

        canvas.drawBitmap(bitmap,bitmapX,bitmapY,paint);
        if(bitmap.isRecycled()){//判断图片是否回收
            bitmap.recycle();//强制回收
        }
    }


    @Override
    public boolean performClick() {
        return super.performClick();
    }
}

//avtivity:

package com.zengjx.androidbaseproject;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.event.Touch.HatView;

public class TouchEventActivity extends AppCompatActivity {
 HatView hat ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_touch_event);
        hat=  new HatView(TouchEventActivity.this); // 创建并实例化HatView类
        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativelayout); // 获取相对局管理器

        // 为帽子添加触摸事件监听
        hat.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                hat.bitmapX = event.getX()-88; // 设置帽子显示位置的X坐标
                hat.bitmapY = event.getY()-33; // 设置帽子显示位置的Y坐标
                hat.invalidate(); // 重绘hat组件
                return true;
            }
        });
        relativeLayout.addView(hat); //将hat添加到布局管理器中
    }


}  单击事件与触摸事件的区别:

 会先响应触摸事件,如果触摸事件返回 true 则 单击事件不会响应。如果触摸事件返回 false 则 单击事件不会响应。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.touch_key);
    button=findViewById(R.id.btn_touchkey);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.i("touch","单击事件") ;
        }
    });

    button.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            Log.i("touch","触摸事件") ;
            switch (motionEvent.getAction()){
                case MotionEvent.ACTION_DOWN:
                    Log.i("touch","按下") ;
                    break;
                case MotionEvent.ACTION_MOVE:
                    break;
                case MotionEvent.ACTION_UP:
                    Log.i("touch","抬起") ;
                    button.performClick();
                    break;
            }
            Log.i("touch","返回 flase") ;
            return false;
        }




    });


}
//但是日志信息:触摸离开 还是会有 单击事件

警告:setOnTouchListener

Custom view `Button` has setOnTouchListener called on it but does not override performClick less... (Ctrl+F1) 
If a View that overrides onTouchEvent or uses an OnTouchListener does not also 
implement performClick and call it when clicks are detected, the View may not handle 
accessibility actions properly. Logic handling the click actions should ideally 
be placed in View#performClick 
as some accessibility services invoke performClick when a click action should occur.

相关 博客:https://blog.csdn.net/qq_32916805/article/details/78567651

猜你喜欢

转载自blog.csdn.net/oDianZi1234567/article/details/85128233