按我測試的是什麼:哪個事件在android系統被觸發時,鍵盤是開放的,我們後退按鈕
在Android中的鍵盤時,沒有打開,我們按後退按鈕。 onBackPressed()
事件被觸發
問題
情景-A:在Android上的鍵盤被打開,我們按後退按鈕時。鍵盤被關閉。 onBackPressed()
不會觸發
注:首次onBackPressed()
不叫這裏 ...只有鍵盤是不可見的onBackPressed()
被稱爲
如何通過編程模擬情景-A
按我測試的是什麼:哪個事件在android系統被觸發時,鍵盤是開放的,我們後退按鈕
在Android中的鍵盤時,沒有打開,我們按後退按鈕。 onBackPressed()
事件被觸發
問題
情景-A:在Android上的鍵盤被打開,我們按後退按鈕時。鍵盤被關閉。 onBackPressed()
不會觸發
注:首次onBackPressed()
不叫這裏 ...只有鍵盤是不可見的onBackPressed()
被稱爲
如何通過編程模擬情景-A
上BackKeyPress檢查軟鍵盤是否通過講座敬愛的 段開放,如果開放,然後將其關閉並阻止onBackPressed(),如果沒有調用 onBackPressed()
final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
//r will be populated with the coordinates of your view that area still visible.
activityRootView.getWindowVisibleDisplayFrame(r);
int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
... close soft keyboard from here
}
}
});
onBackPressed()
不會被調用時,鍵盤顯示並關閉。不知道確切的原因,但這是事實。
但是,如果您需要在顯示鍵盤時捕獲後退按下事件,則可以偵聽根/父佈局可見性中的更改。
重申@ReubenScratton誰給優秀answer克服這個問題,我們有這樣的代碼:
final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
if (heightDiff > dpToPx(this, 200)) { // if more than 200 dp, it's probably a keyboard...
// ... do something here
}
}
});
和dpToPx
功能:
public static float dpToPx(Context context, float valueInDp) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
}
相關:http://stackoverflow.com/questions/ 3940127 /從軟鍵盤截取的回退按鈕 –
檢查了這一點。它解決了同樣的問題,我有[https://stackoverflow.com/a/36259261/5130987](https://stackoverflow.com/a/36259261/5130987) –