2017-02-21 27 views
2

按我测试的是什么:哪个事件在android系统被触发时,键盘是开放的,我们后退按钮

在Android中的键盘时,没有打开,我们按后退按钮。 onBackPressed()事件被触发

问题

情景-A:在Android上的键盘被打开,我们按后退按钮时。键盘被关闭。 onBackPressed()不会触发

首次onBackPressed()不叫这里 ...只有键盘是不可见的onBackPressed()被称为

如何通过编程模拟情景-A

+0

相关:http://stackoverflow.com/questions/ 3940127 /从软键盘截取的回退按钮 –

+0

检查了这一点。它解决了同样的问题,我有[https://stackoverflow.com/a/36259261/5130987](https://stackoverflow.com/a/36259261/5130987) –

回答

0

上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 
     } 
    } 
    }); 
0

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); 
} 
相关问题