亲宝软件园·资讯

展开

Android事件与手势操作详解

上后左爱 人气:0

事件和手势

事件处理 :

物理事件处理

基于回调的时间处理: 重写Activity 回调方法

OnTouchEvent + OnKeyDown + OnKeyUp

基于回调处理事件,采用通用性 事件 比如在物理按键

1.物理事件 提供三个事件 :

按下 : OnkeyDown, OnKeyUp: ONKeyLongPress(): 长按键

Android 当中位每个物理按键提供关键字常量: keyCODE_MENU,KEYCODE_HOME

案例: 连续按两次返回键返回地图

package com.example.myapplication;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
/**
 * 功能: 连续按两次返回键 退出当前应用
 */
public class MainActivity extends AppCompatActivity {
    private long exitTime = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            // 执行退出方法,
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    public void exit() {
        if( (System.currentTimeMillis() - exitTime ) > 2000){
            Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        }else{
            finish();
            System.exit(0);
        }
    }
}

触摸事件

OnTouchEvent ()

package com.example.myapplication;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
import androidx.appcompat.app.AppCompatActivity;
/**
 * 功能: 通过Touch 移动帽子 给企鹅带帽子
 * 1. s实例自顶HatView 在图中 显示帽子位置
 * 2. 通过监听OnTouchEvent 不断更新 X,Y 坐标
 * 3. 将帽子布局管理器中,动态天剑
 */
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 添加帽子对象,触摸事件监听器
        final HatView hatView = new HatView(MainActivity.this);
        hatView.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                hatView.bitmapX = motionEvent.getX()- 80; // 减去帽子一般高度,中心点移动
                hatView.bitmapY = motionEvent.getY();
                // 冲新绘制
                hatView.invalidate();
                return true;
            }
        });
        RelativeLayout relativeLayout = findViewById(R.id.relativeLayout);
        relativeLayout.addView(hatView);
    }
}
package com.example.myapplication;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
/**
 *   Hat Postition  通过Touch 方式 移动
 * */
public class HatView extends View {
    public float bitmapX;
    public float bitmapY;
    public HatView(Context context) {
        super(context);
        this.bitmapX = 0.0f;
        this.bitmapY = 0.0f;
    }
    /**
     *  重新绘制帽子
     * */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.hat);
        canvas.drawBitmap(bitmap,bitmapX,bitmapY,paint);
        if(bitmap.isRecycled()){
            bitmap.recycle();
        }
    }
}

手势检测

1.Android 为手势检测提供一个 GestureDetector.onGestureListener

手势监听器 必须重写其六个方法,onDown,OnFling(用户手指在触摸屏拖过触发),OnLongPress

OnScroll,onShowPress,onSingleTapUp(用户手指在屏幕上亲敲击触发)

实例用户的触发功能:

package com.example.myapplication;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ViewFlipper;
import androidx.appcompat.app.AppCompatActivity;
/**
  * 手势方式滑动动画
 */
public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
    ViewFlipper flipper; //定义ViewFlipper
    GestureDetector detector; //定义手势检测器
    Animation[] animation = new Animation[4];//定义动画数组,为ViewFlipper指定切换动画
    final int distance = 50; //定义手势动作两点之间最小距离
    //定义图片数组
    private int[] images = new int[]{R.drawable.img01, R.drawable.img02, R.drawable.img03,
            R.drawable.img04,
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        detector = new GestureDetector(MainActivity.this, this);
        // 将显示的动画加入ViewFlipper 当中,并且初始化动画数组
        flipper = findViewById(R.id.flipper);
        for(int i= 0; i< images.length; i++){
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(images[i]);
            flipper.addView(imageView);
        }
        // 加载动画资源组件
        animation[0] = AnimationUtils.loadAnimation(this, R.anim.slide_in_left);
        animation[1] = AnimationUtils.loadAnimation(this, R.anim.slide_out_left);
        animation[2] = AnimationUtils.loadAnimation(this, R.anim.slide_in_right);
        animation[3] = AnimationUtils.loadAnimation(this, R.anim.slide_out_right);
    }
    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }
    @Override
    public void onShowPress(MotionEvent motionEvent) {
    }
    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }
    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }
    @Override
    public void onLongPress(MotionEvent motionEvent) {
    }
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float v, float v1) {
        // 通过触摸坐标的 判断滑动趋势
        if ((e1.getX() - e2.getX()) > distance){
            flipper.setInAnimation(animation[2]);
            flipper.setAnimation(animation[1]);
            flipper.showPrevious();
            return  true;
        }else if (e2.getX() - e1.getX() > distance) {
            //为flipper设置切换的动画
            flipper.setInAnimation(animation[0]);
            flipper.setOutAnimation(animation[3]);
            flipper.showNext();
            return true;
        }
        return false;
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return detector.onTouchEvent(event);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
    <ViewFlipper
        android:id = "@+id/flipper"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ViewFlipper>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:fromXDelta="-100%p"
    android:toXDelta="0"
    android:duration="500"/>
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="500"
        android:fromXDelta="100%p"
        android:toXDelta="0"/>

</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="500"
        android:fromXDelta="0"
        android:toXDelta="-100%p"/>
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="500"
        android:fromXDelta="0"
        android:toXDelta="100%p"/>
</set>

手势添加

自定义的手势:

Getsures Builder 手势应用APP

总结:

1. GestureLibararias 加载 自定义的 手势库

2. 获取GestureOverlayView 设置其事件监听器

3. 从GestureOverlayView 所有的手势预测只,得到里面最大值 打分

4. 从edito编辑框原来的值,与判断打分最高值手势相加 会写到原来的编辑框中

package com.example.myapplication;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.Prediction;
import android.graphics.Color;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
/**
  * 手势方式滑动动画
 */
public class MainActivity extends AppCompatActivity implements GestureOverlayView.OnGesturePerformedListener {
    private GestureDetector detector;
    private GestureLibrary librarry;
    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 加载自定义手势文件, 不成功退出
        librarry = GestureLibraries.fromRawResource(MainActivity.this, R.raw.gestures);
        editText = findViewById(R.id.editText);
        if(!librarry.load()){
            finish();
        }
        // 获取GestureOverlayView 设置其事件监听器
        GestureOverlayView gestureOverlayView = findViewById(R.id.gesture);
        gestureOverlayView.setGestureColor(Color.BLACK);
        gestureOverlayView.setFadeOffset(1000);
        gestureOverlayView.addOnGesturePerformedListener(MainActivity.this);
    }
    @Override
    public void onGesturePerformed(GestureOverlayView gestureOverlayView, Gesture gesture) {
        // 获取其最佳匹配,并更新编辑栏
        ArrayList<Prediction> predictions = librarry.recognize(gesture);
        int index = 0;// 保存当前预测的索引号
        double score = 0.0;// 保存当前预测的得分
        for (int i = 0; i < predictions.size(); i++) {// 获得最佳匹配结果
            Prediction result = predictions.get(i);// 获得一个预测结果
            if (result.score > score) {
                index = i;
                score = result.score;
            }
        }
        String Text = editText.getText().toString();
        Text += predictions.get(index).name;
        editText.setText(Text);
    }
}

<?xml version="1.0" encoding="utf-8"?>

<EditText
    android:id="@+id/editText"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="40dp"
    android:layout_marginTop="190dp" />
<android.gesture.GestureOverlayView
    android:id="@+id/gesture"
    android:layout_width="320dp"
    android:layout_height="180dp"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="85dp"
    android:gestureStrokeType="multiple" />

加载全部内容

相关教程
猜你喜欢
用户评论