[英]Android: how to capture long press event on soft input/keyboard?
問題的簡短版本:如何在Android中的軟輸入/鍵盤上捕獲長按事件?
長版:在Android應用程序中,我們有一個多行EditText,我們希望有這樣的行為:1。默認情況下,它顯示DONE按鈕,通過點擊它,軟輸入/鍵盤將被關閉。 2.如果用戶長按DONE按鈕,其行為將更改為ENTER按鈕,EditText中將有一個新行。
對於需求#1,我在這里使用了解決方案: https : //stackoverflow.com/a/12570003/4225326
對於需求#2,我遇到的阻塞問題是,如何捕獲長按事件。 我設置了onEditorActionListener,但捕獲的事件為null: http : //developer.android.com/reference/android/widget/TextView.OnEditorActionListener.html我搜索了文檔,長按相關的方法是針對硬鍵盤: http:http: //developer.android.com/reference/android/view/View.html#onKeyLongPress(int,android.view.KeyEvent ),我找不到一個用於軟輸入/鍵盤。
感謝您查看此問題。
我自己找不到這個答案,所以我手動編寫了解決方案。 我在KeyboardView.OnKeyboardActionListener
的onPress()
和onRelease()
事件上使用了一個計時器。 這是重要的代碼。 為簡潔起見,遺漏了許多TRY / CATCH。 在英語中,當按下某個鍵時,我正在啟動一個計時器,它等待通常等待的長按事件( ViewConfiguration.getLongPressTimeout()
),然后在原始線程上執行on-long-click事件。 隨后的按鍵釋放和按鍵可以取消任何活動計時器。
public class MyIME
extends InputMethodService
implements KeyboardView.OnKeyboardActionListener {
:
:
private Timer timerLongPress = null;
:
:
@Override
public void onCreate() {
super.onCreate();
:
:
timerLongPress = new Timer();
:
:
}
@Override
public void onRelease(final int primaryCode) {
:
:
timerLongPress.cancel();
:
:
}
@Override
public void onPress(final int primaryCode) {
:
:
timerLongPress.cancel();
:
:
timerLongPress = new Timer();
timerLongPress.schedule(new TimerTask() {
@Override
public void run() {
try {
Handler uiHandler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
MyIME.this.onKeyLongPress(primaryCode);
} catch (Exception e) {
Log.e(MyIME.class.getSimpleName(), "uiHandler.run: " + e.getMessage(), e);
}
}
};
uiHandler.post(runnable);
} catch (Exception e) {
Log.e(MyIME.class.getSimpleName(), "Timer.run: " + e.getMessage(), e);
}
}
}, ViewConfiguration.getLongPressTimeout());
:
:
}
public void onKeyLongPress(int keyCode) {
// Process long-click here
}
通過擴展KeyboardView類來創建自定義鍵盤視圖類。 覆蓋onLongPress()方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.