在文字欄位中使用觸控筆輸入內容

Jetpack androidx.compose.material3 程式庫可讓使用者使用觸控筆,在任何應用程式中寫入任何 TextField 元件。

圖 1. 使用觸控筆手寫輸入。

如要預設啟用觸控筆輸入功能,請將程式庫依附元件新增至應用程式的 build.gradle 檔案:

Kotlin

dependencies {
    implementation("androidx.compose.foundation:foundation:1.7.0")
}

android {
    buildFeatures {
        compose = true
    }

    composeOptions {
        kotlinCompilerExtensionVersion = "1.1.1"
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }
}

Groovy

dependencies {
    implementation 'androidx.compose.foundation:foundation:1.7.0'
}

android {
    buildFeatures {
        compose true
    }

    composeOptions {
        kotlinCompilerExtensionVersion = "1.1.1"
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }
}

TextField

根據預設,Android 14 以上版本和 androidx.compose.foundation:foundation:1.7.0 依附元件的所有 TextField 元件都會啟用觸控筆手寫功能。如果在元件的手寫範圍內偵測到觸控筆動作事件,系統就會啟動 TextField 的手寫模式。

手寫邊界包括 40 dp 的垂直邊框間距,以及輸入欄位周圍 10 dp 的水平邊框間距。

包含矩形的輸入欄位,用來表示偵測觸控筆動作事件的邊界。
圖 2. TextField 元件的手寫範圍。

透過 KeyboardType.Password 要求輸入法編輯器時,TextField 欄位不支援觸控筆手寫。

輸入委派

應用程式可以顯示顯示為文字輸入欄位的預留位置 UI 元素,但實際上是不具文字輸入功能的靜態 UI 元素。搜尋欄位也是常見的範例。輕觸靜態 UI 元素會觸發轉換至新 UI,其中包含可聚焦輸入欄位的可運作文字輸入欄位。

圖 3. 從靜態 UI 元素到文字輸入欄位的輸入委派。

觸控筆輸入委派

使用手寫委派 API,為預留位置輸入欄位支援觸控筆手寫輸入 (請參閱 handwritingDetectorhandwritingHandler)。預留位置 UI 元素已設為將手寫內容委派給函式輸入欄位。如需實作範例,請參閱 HandwritingDetectorSample.kt

當函式輸入欄位取得焦點並建立 InputConnection 時,系統就會啟動觸控筆手寫模式。

圖 4. 從靜態 UI 元素到文字輸入欄位的觸控筆輸入委派。

測試

觸控筆手寫功能適用於搭載相容觸控筆輸入裝置的 Android 14 以上版本裝置,以及支援 Android 14 觸控筆手寫 API 的輸入法編輯器 (IME)。

如果您沒有觸控筆輸入裝置,請使用以下 Android Debug Bridge (ADB) 指令,在任何具備 Root 存取權的裝置 (包括模擬器) 上模擬觸控筆輸入:


// Android 14
adb shell setprop persist.debug.input.simulate_stylus_with_touch true && adb shell stop && adb shell start

// Android 15 and higher
// Property takes effect after screen reconfiguration such as orientation change.
adb shell setprop debug.input.simulate_stylus_with_touch true

如果您使用的裝置不支援觸控筆,請使用 Gboard Beta 版進行測試。

其他資源