2017-02-11 77 views
0

我正在使用Google的新设计支持库中的FAB。我有一个长形式和FAB屏幕。我希望软键盘打开时FAB消失。无法找到检测软键盘打开的方法。是否有任何其他选项FAB在编辑文本点击时作出响应,FAB出现键盘

我不能侦听器设置为EditText的都包含在一个不同的Fragment S和焦点变化监听器是不是在另一个Fragment的可用。

我已经在主Activity中实现了FAB,所以我无法隐藏关键板监听器EditText重点监听器任何人都可以请一个解决方案与我分享。

回答

2

有软键盘打开时就知道没有直接的方法,但你可以做到以下几点:

contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
@Override 
public void onGlobalLayout() { 

    Rect r = new Rect(); 
    contentView.getWindowVisibleDisplayFrame(r); 
    int screenHeight = contentView.getRootView().getHeight(); 

    // r.bottom is the position above soft keypad or device button. 
    // if keypad is shown, the r.bottom is smaller than that before. 
    int keypadHeight = screenHeight - r.bottom; 

    if (keypadHeight > screenHeight * 0.15) { 
     // keyboard is opened 
     // Hide your FAB here 
    } 
    else { 
     // keyboard is closed 
    } 
} 
}); 
+0

感谢Zed的。我通过你的代码解决了这个问题...... –

+0

使用视图分页器我实现了mutilple分片如何使用这段代码可以告诉我。我尝试过,但晶圆厂突然打开并关闭,然后晶圆厂在主要活动中显示所有碎片 –

0

你可以监听键盘的开启和关闭。在这个问题上所列

public class BaseActivity extends Activity { 
private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
     int heightDiff = rootLayout.getRootView().getHeight() - rootLayout.getHeight(); 
     int contentViewTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); 

     LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(BaseActivity.this); 

     if(heightDiff <= contentViewTop){ 
      onHideKeyboard(); 

      Intent intent = new Intent("KeyboardWillHide"); 
      broadcastManager.sendBroadcast(intent); 
     } else { 
      int keyboardHeight = heightDiff - contentViewTop; 
      onShowKeyboard(keyboardHeight); 

      Intent intent = new Intent("KeyboardWillShow"); 
      intent.putExtra("KeyboardHeight", keyboardHeight); 
      broadcastManager.sendBroadcast(intent); 
     } 
    } 
}; 

private boolean keyboardListenersAttached = false; 
private ViewGroup rootLayout; 

protected void onShowKeyboard(int keyboardHeight) {} 
protected void onHideKeyboard() {} 

protected void attachKeyboardListeners() { 
    if (keyboardListenersAttached) { 
     return; 
    } 

    rootLayout = (ViewGroup) findViewById(R.id.rootLayout); 
    rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener); 

    keyboardListenersAttached = true; 
} 

@Override 
protected void onDestroy() { 
    super.onDestroy(); 

    if (keyboardListenersAttached) { 
     rootLayout.getViewTreeObserver().removeGlobalOnLayoutListener(keyboardLayoutListener); 
    } 
} 
} 

更详细的例子:SoftKeyboard open and close listener in an activity in Android?