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
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...