首页 > 其他分享 >Android 手势相关(二)

Android 手势相关(二)

时间:2024-03-29 17:23:28浏览次数:25  
标签:Toast mStore GestureOverlayView 相关 Android 手势 public gesture

Android 手势相关(二)

本篇文章继续记录下android 手势相关的内容.

1: GestureOverlayView简介

GestureOverlayView是Android中的一个视图组件,用于捕捉和处理手势操作.

GestureOverlayView的主要用途:

  1. 手势识别: 通过GestureOverlayView,保存一些手势,并堆用户手势操作进行识别匹配.
  2. 手势绘制: 我们还可以在GestureOverlayView绘制,并保存绘制路径或者手势.
  3. 手势交互: 我们可以监听手势的开始,结束等事件.

本文主要介绍的是手势识别这块,实现的效果就是设置手势的名称, 保存手势, 绘制手势判断是否匹配.

2: 布局

界面布局主要有几块:

  1. EditText 用于设置手势名称
  2. btn1用于设置保存手势动作
  3. btn2用于设置匹配手势动作
  4. GestureOverlayView用于手势绘制.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".GestureActivity">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:hint="请输入保存手势的名称"
        android:id="@+id/edit_name"
        />
    <Button
        android:id="@+id/btn_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存手势"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/edit_name"
        />

    <Button
        android:id="@+id/btn_compare"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="匹配手势"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_save" />

    <android.gesture.GestureOverlayView
        android:id="@+id/gesture"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:background="#aaaaaa"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_compare" />
</androidx.constraintlayout.widget.ConstraintLayout>

GestureOverlayView在xml定义的属性可以查看下attrs.xml.

<!-- GestureOverlayView specific attributes. These attributes are used to configure
     a GestureOverlayView from XML. -->
<declare-styleable name="GestureOverlayView">
    <!-- Width of the stroke used to draw the gesture. -->
    <attr name="gestureStrokeWidth" format="float" />
    <!-- Color used to draw a gesture. -->
    <attr name="gestureColor" format="color" />
    <!-- Color used to draw the user's strokes until we are sure it's a gesture. -->
    <attr name="uncertainGestureColor" format="color" />
    <!-- Time, in milliseconds, to wait before the gesture fades out after the user
         is done drawing it. -->
    <attr name="fadeOffset" format="integer" />
    <!-- Duration, in milliseconds, of the fade out effect after the user is done
         drawing a gesture. -->
    <attr name="fadeDuration" format="integer" />
    <!-- Defines the type of strokes that define a gesture. -->
    <attr name="gestureStrokeType">
        <!-- A gesture is made of only one stroke. -->
        <enum name="single" value="0" />
        <!-- A gesture is made of multiple strokes. -->
        <enum name="multiple" value="1" />
    </attr>
    <!-- Minimum length of a stroke before it is recognized as a gesture. -->
    <attr name="gestureStrokeLengthThreshold" format="float" />
    <!-- Squareness threshold of a stroke before it is recognized as a gesture. -->
    <attr name="gestureStrokeSquarenessThreshold" format="float" />
    <!-- Minimum curve angle a stroke must contain before it is recognized as a gesture. -->
    <attr name="gestureStrokeAngleThreshold" format="float" />
    <!-- Defines whether the overlay should intercept the motion events when a gesture
         is recognized. -->
    <attr name="eventsInterceptionEnabled" format="boolean" />
    <!-- Defines whether the gesture will automatically fade out after being recognized. -->
    <attr name="fadeEnabled" format="boolean" />
    <!-- Indicates whether horizontal (when the orientation is vertical) or vertical
         (when orientation is horizontal) strokes automatically define a gesture. -->
    <attr name="orientation" />
</declare-styleable>

这里我只用到了gestureStrokeWidth,gestureColor两个属性,并且是在代码中设置的.

3: GestureLibrary对象

GestureLibrary 是android 中用于保存和管理手势的类. 源码很简单,具体的方法有兴趣的都去试下

public abstract class GestureLibrary {
    protected final GestureStore mStore;

    protected GestureLibrary() {
        mStore = new GestureStore();
    }

    public abstract boolean save();

    public abstract boolean load();

    public boolean isReadOnly() {
        return false;
    }

    /** @hide */
    public Learner getLearner() {
        return mStore.getLearner();
    }

    public void setOrientationStyle(int style) {
        mStore.setOrientationStyle(style);
    }

    public int getOrientationStyle() {
        return mStore.getOrientationStyle();
    }

    public void setSequenceType(int type) {
        mStore.setSequenceType(type);
    }

    public int getSequenceType() {
        return mStore.getSequenceType();
    }

    public Set<String> getGestureEntries() {
        return mStore.getGestureEntries();
    }

    public ArrayList<Prediction> recognize(Gesture gesture) {
        return mStore.recognize(gesture);
    }

    public void addGesture(String entryName, Gesture gesture) {
        mStore.addGesture(entryName, gesture);
    }

    public void removeGesture(String entryName, Gesture gesture) {
        mStore.removeGesture(entryName, gesture);
    }

    public void removeEntry(String entryName) {
        mStore.removeEntry(entryName);
    }

    public ArrayList<Gesture> getGestures(String entryName) {
        return mStore.getGestures(entryName);
    }
}

创建对象:

gestureLibrary = GestureLibraries.fromFile("sdcard/gesture");

根据路径创建gestureLibrary创建对象. 这里无需关注文件是否存在,save方法会有判断:

public boolean save() {
    if (!mStore.hasChanged()) return true;

    final File file = mPath;

    final File parentFile = file.getParentFile();
    if (!parentFile.exists()) {
        if (!parentFile.mkdirs()) {
            return false;
        }
    }

    boolean result = false;
    try {
        //noinspection ResultOfMethodCallIgnored
        file.createNewFile();
        mStore.save(new FileOutputStream(file), true);
        result = true;
    } catch (FileNotFoundException e) {
        Log.d(LOG_TAG, "Could not save the gesture library in " + mPath, e);
    } catch (IOException e) {
        Log.d(LOG_TAG, "Could not save the gesture library in " + mPath, e);
    }

    return result;
}

由于是文件操作,权限不能忘记:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

4: GestureOverlayView

GestureOverlayView提供了三个接口实现:

  1. addOnGestureListener(OnGestureListener listener)
  2. addOnGesturePerformedListener(OnGesturePerformedListener listener)
  3. addOnGesturingListener(OnGesturingListener listener)

这里我们使用addOnGesturePerformedListener,将手势识别器与手势监听器关联:

gestureOverlayView.setGestureColor(R.color.teal_200);
gestureOverlayView.setGestureStrokeWidth(5);
gestureOverlayView.addOnGesturePerformedListener(new GestureOverlayView.OnGesturePerformedListener() {
    @Override
    public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
 		  //处理手势执行 
    }
}

onGesturePerformed方法中我们做两个操作:

  1. 保存手势
  2. 判断手势匹配

保存手势的操作:

根据onGesturePerformed回调的gesture,我们调用gestureLibrary.addGesture添加手势,并调用gestureLibrary.save()进行保存.

gestureLibrary.addGesture(editText.getText().toString(), gesture);
if (gestureLibrary.save()) {
    Toast.makeText(GestureActivity.this, "保存手势成功", Toast.LENGTH_LONG).show();
}else{
    Toast.makeText(GestureActivity.this, "保存手势失败", Toast.LENGTH_LONG).show();
}

判断匹配:

调用recognize方法,传入一个手势参数,返回与参数手势最匹配的手势,

Prediction.score是用来表示手势匹配的置信度或相似度的指标,

它是一个浮点数,范围通常是0到10之间,表示匹配的程度.

ArrayList<Prediction> recognize = gestureLibrary.recognize(gesture);
Prediction prediction = recognize.get(0);
if (prediction.score >= 2) {
    Toast.makeText(GestureActivity.this, prediction.name + "匹配成功", Toast.LENGTH_SHORT).show();
} else {
    Toast.makeText(GestureActivity.this, prediction.name + "匹配失败", Toast.LENGTH_SHORT).show();
}

完整的代码如下:

public class GestureActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "GestureActivity";
    private GestureOverlayView gestureOverlayView;
    private Button btnSave, btnCompare;
    private int status = 0; // 1:保存手势 2: 手势比较
    private GestureLibrary gestureLibrary;
    private EditText editText;

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gesture);
        gestureOverlayView = findViewById(R.id.gesture);
        btnSave = findViewById(R.id.btn_save);
        btnCompare = findViewById(R.id.btn_compare);
        editText = findViewById(R.id.edit_name);
        gestureLibrary = GestureLibraries.fromFile("sdcard/gesture");
        btnSave.setOnClickListener(this);
        btnCompare.setOnClickListener(this);
        gestureOverlayView.setGestureColor(R.color.teal_200);
        gestureOverlayView.setGestureStrokeWidth(5);
        gestureOverlayView.addOnGesturePerformedListener(new GestureOverlayView.OnGesturePerformedListener() {
            @Override
            public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
                if (status == 1) {//保存手势
                    if (gesture == null || gesture.getLength() <= 0) return;
                    if (TextUtils.isEmpty(editText.getText().toString())) {
                        Toast.makeText(GestureActivity.this, "请输入手势名称", Toast.LENGTH_LONG).show();
                        return;
                    }
                    gestureLibrary.addGesture(editText.getText().toString(), gesture);
                    if (gestureLibrary.save()) {
                        Toast.makeText(GestureActivity.this, "保存手势成功", Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(GestureActivity.this, "保存手势失败", Toast.LENGTH_LONG).show();
                    }
                } else if (status == 2) {//比较手势
                    ArrayList<Prediction> recognize = gestureLibrary.recognize(gesture);
                    Prediction prediction = recognize.get(0);
                    if (prediction.score >= 2) {
                        Toast.makeText(GestureActivity.this, prediction.name + "匹配成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(GestureActivity.this, prediction.name + "匹配失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_compare:
                status = 2;
                break;
            case R.id.btn_save:
                status = 1;
                break;
        }
    }
}

本文由博客一文多发平台 OpenWrite 发布!

标签:Toast,mStore,GestureOverlayView,相关,Android,手势,public,gesture
From: https://www.cnblogs.com/zhjing/p/18104249

相关文章

  • Android.bp语法记录
    参考资料:https://www.cnblogs.com/linhaostudy/p/12361659.htmlhttps://blog.csdn.net/hxp1994/article/details/113853459https://blog.csdn.net/tkwxty/article/details/104395820 Android.bpAndroid.bp文件首先是Android系统的一种编译配置文件,是用来代替原来的Android.......
  • android小球(二)——用户数据缓存详解SharedPreferences
    SharedPreferences概述SharedPreferences是Android平台上一个轻量级的存储辅助类,用来保存应用的一些常用配置,它提供了String,set,int,long,float,boolean六种数据类型。使用SharedPreferences进行存储的数据是存放在一个XML文件中的,同时它的存储方式是是以key-value的形式,key对应......
  • android AVC错误修改权限方法
    adblogcat日志报错:init:avc:denied{set}forproperty=camera.gc02m1scontext=u:r:mm-qcamerad:s0tcontext=u:object_r:camera_prop:s0tclass=property_serviceSELinux的权限不足标志性log:avc:denied{操作权限}forpid=7201comm=“进程名”scontext=u......
  • Android杂项知识记录
    Android启动流程:https://blog.csdn.net/xingyu19911016/article/details/120023396https://blog.csdn.net/ldxlz224/article/details/123238353init进程为第一个用户级别的进程,PID为1,它通过一系列的初始工作以及解析init.rc(一个脚本文件)文件构建出Android系统运行的初始......
  • [转帖]软件出口管制中的相关法律问题和分析
    https://www.sohu.com/a/294379160_221481 作者|方春晖刘良勇宋献涛 北京德和衡律师事务所(本文系知产力获得独家首发的稿件,转载须征得作者本人同意,并在显要位置注明文章来源。)(本文8010字,阅读约需16分钟)序言在国际贸易争端进程中,出口管制合规方面的话题不断浮现出来......
  • ssm基于Android的XX校园交流APP
    摘要随着互联网时代的发展,传统管理技术已无法高效,便捷地管理信息。为了迎合时代需求,优化管理效率,各种各样的管理系统应运而生,随着各行业的不断发展,XX校园交流APP建设也逐渐进入了信息化的进程。这个App的设计主要包括前台页面的设计和方便用户互动的后端数据库,而前端软件......
  • 【全开源】JAVA游戏陪玩系统源码陪练APP源码H5源码电竞系统源码支持Android+IOS+H5_博
    “游戏陪玩系统源码、陪练APP源码、H5源码及电竞系统源码”,这些创新技术的融合,为电竞爱好者与游戏玩家带来前所未有的互动体验。通过我们的源码,您可以轻松搭建起一个功能完备的游戏陪玩平台,无论是寻找技术高超的陪练,还是与志同道合的玩家组队竞技,都能在这个平台上得到满足。同......
  • 【全开源】JAVA多商户运营版商城系统源码地摊兄源码多商户源码社交电商源码支持Androi
    "多商户运营版商城系统源码——地摊兄源码多商户源码社交电商源码",是现今电商领域的一大突破。此源码设计独特,功能全面,既满足了多商户运营的需求,又融入了社交电商的理念。通过这套源码,商家可以轻松搭建起一个功能强大的电商平台,实现多商户的集中管理与运营,提升整体运营效率和用......
  • 【全开源】JAVA同城服务美容美发到店服务上门服务系统源码支持Android+IOS+H5_博纳软
    “同城服务美容美发到店服务上门服务系统”,这一创新服务模式正日益受到消费者的青睐。该系统以同城为范围,整合了美容美发行业的优质资源,为消费者提供了便捷、高效的到店与上门服务选择。无论是忙碌的上班族还是行动不便的老年人,只需轻轻一点,即可享受到专业的美容美发服务。同时......
  • [RK3399-Android10] 关于USB触摸屏休眠状态无法唤醒设备的一种情况
    问题描述RK3399Android10平台上,USB触摸屏在系统按键休眠之后,无法触摸唤醒设备。查看内核日志,发现休眠之后,USB设备直接断开,lsusb发现不了设备。休眠之后host接口没有断开电源,使用USB鼠标插在同一个接口上,USB鼠标可以正常唤醒设备。问题描述之前遇到这样的问题一般是修改s......