2017-02-11 20 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?