Android 手勢相關(二)

来源:https://www.cnblogs.com/zhjing/p/18104249
-Advertisement-
Play Games

Android 手勢相關(二) 本篇文章繼續記錄下android 手勢相關的內容. 1: GestureOverlayView簡介 GestureOverlayView是Android中的一個視圖組件,用於捕捉和處理手勢操作. GestureOverlayView的主要用途: 手勢識別: 通過Ges ...


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 發佈!


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 什麼是哈希桶 Redis中的哈希桶是一種數據結構,用於在Redis的哈希表(如字典結構)中存儲鍵值對。哈希桶是哈希表數組中的每個元素,可以視為一個容器或槽位,用於存放數據。在Redis中,當插入一個新的鍵值對時,會根據鍵的哈希值計算出一個索引,該索引指向特定的哈希桶。 每個哈希桶可以存儲多個鍵值對, ...
  • 在金融行業數字化轉型背景下,銀行等金融機構面臨著業務模式創新與數據應用的深度融合。業務上所需要的不再是單純的數據,而是數據背後映射的業務趨勢洞察,只有和業務相結合轉化為業務度量指標,經過數據分析處理呈現為報表進行展示,才能真正體現它們的價值。 但在需求轉化為指標的過程中,存在需求管理雜亂、登記維護難 ...
  • 企業搭建完善、全面的指標體系是企業用數據指導業務經營決策的第一步。但是做完指標之後,對指標的監控,經常被大家忽視。當指標發生了異常波動(上升或下降),需要企業能夠及時發現,並快速找到背後真實的原因,才能針對性地制定相應策略,否則就是盲打,原地打轉。 指標異常波動的具體場景,比如: · 企業關鍵詞的搜 ...
  • 【Pavia】遙感圖像數據集下載地址和讀取數據集代碼 目錄【Pavia】遙感圖像數據集下載地址和讀取數據集代碼前言Pavia數據集Pavia數據集地址:Pavia數據集預覽PaviaU.matPaviaU_gt.matPavia數據集的Matlab讀取方式Pavia數據集中PaviaU.mat的ma ...
  • 要求統計所有分類下的數量,如果分類下沒有對應的數據也要展示。這種問題在日常的開發中很常見,每次寫每次忘,所以在此記錄下。 這種統計往往不能直接group by,因為有些類別可能沒有對應的數據 這裡有兩個思路(如果您有更好的方法,請一定要告訴我,求求了): 每種類型分別統計,用union 連接(比較適 ...
  • 一、Button Button(按鈕)是一種常見的用戶界面控制項,通常用於觸發操作或提交數據。Button 擁有文本標簽和一個可點擊的區域,用戶點擊該區域即可觸發相應的操作或事件。 Button 的主要功能有: 觸發操作:用戶點擊 Button 可以觸發相應的操作,例如提交表單、搜索、切換頁面等。 ...
  • 一、Swiper 1.概述 Swiper可以實現手機、平板等移動端設備上的圖片輪播效果,支持無縫輪播、自動播放、響應式佈局等功能。Swiper輪播圖具有使用簡單、樣式可定製、功能豐富、相容性好等優點,是很多網站和移動應用中常用的輪播圖插件。 2.佈局與約束 Swiper是一個容器組件,如 ...
  • 一、Grid/GridItem 1.概述 網格佈局是一種新型的佈局方式,它按照網格來劃分頁面,通過列和行來定義網格,使得頁面的佈局更加靈活、簡潔、易於維護。網格佈局能夠將頁面分成多個單元格,可以在這些單元格中佈置各種元素,例如文本、圖片、媒體等,從而實現頁面的排版。網格佈局支持自適應佈局,能 ...
一周排行
    -Advertisement-
    Play Games
  • 1、預覽地址:http://139.155.137.144:9012 2、qq群:801913255 一、前言 隨著網路的發展,企業對於信息系統數據的保密工作愈發重視,不同身份、角色對於數據的訪問許可權都應該大相徑庭。 列如 1、不同登錄人員對一個數據列表的可見度是不一樣的,如數據列、數據行、數據按鈕 ...
  • 前言 上一篇文章寫瞭如何使用RabbitMQ做個簡單的發送郵件項目,然後評論也是比較多,也是準備去學習一下如何確保RabbitMQ的消息可靠性,但是由於時間原因,先來說說設計模式中的簡單工廠模式吧! 在瞭解簡單工廠模式之前,我們要知道C#是一款面向對象的高級程式語言。它有3大特性,封裝、繼承、多態。 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 介紹 Nodify是一個WPF基於節點的編輯器控制項,其中包含一系列節點、連接和連接器組件,旨在簡化構建基於節點的工具的過程 ...
  • 創建一個webapi項目做測試使用。 創建新控制器,搭建一個基礎框架,包括獲取當天日期、wiki的請求地址等 創建一個Http請求幫助類以及方法,用於獲取指定URL的信息 使用http請求訪問指定url,先運行一下,看看返回的內容。內容如圖右邊所示,實際上是一個Json數據。我們主要解析 大事記 部 ...
  • 最近在不少自媒體上看到有關.NET與C#的資訊與評價,感覺大家對.NET與C#還是不太瞭解,尤其是對2016年6月發佈的跨平臺.NET Core 1.0,更是知之甚少。在考慮一番之後,還是決定寫點東西總結一下,也回顧一下.NET的發展歷史。 首先,你沒看錯,.NET是跨平臺的,可以在Windows、 ...
  • Nodify學習 一:介紹與使用 - 可樂_加冰 - 博客園 (cnblogs.com) Nodify學習 二:添加節點 - 可樂_加冰 - 博客園 (cnblogs.com) 添加節點(nodes) 通過上一篇我們已經創建好了編輯器實例現在我們為編輯器添加一個節點 添加model和viewmode ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...
  • 類型檢查和轉換:當你需要檢查對象是否為特定類型,並且希望在同一時間內將其轉換為那個類型時,模式匹配提供了一種更簡潔的方式來完成這一任務,避免了使用傳統的as和is操作符後還需要進行額外的null檢查。 複雜條件邏輯:在處理複雜的條件邏輯時,特別是涉及到多個條件和類型的情況下,使用模式匹配可以使代碼更 ...
  • 在日常開發中,我們經常需要和文件打交道,特別是桌面開發,有時候就會需要載入大批量的文件,而且可能還會存在部分文件缺失的情況,那麼如何才能快速的判斷文件是否存在呢?如果處理不當的,且文件數量比較多的時候,可能會造成卡頓等情況,進而影響程式的使用體驗。今天就以一個簡單的小例子,簡述兩種不同的判斷文件是否... ...
  • 前言 資料庫併發,數據審計和軟刪除一直是數據持久化方面的經典問題。早些時候,這些工作需要手寫複雜的SQL或者通過存儲過程和觸發器實現。手寫複雜SQL對軟體可維護性構成了相當大的挑戰,隨著SQL字數的變多,用到的嵌套和複雜語法增加,可讀性和可維護性的難度是幾何級暴漲。因此如何在實現功能的同時控制這些S ...