需求:
現在有一個需求是點擊一行文本框,彈出一個之前隱藏的輸入框,輸入完成后按返回鍵或者其他的東西隱藏鍵盤和輸入框,將輸入框的內容填充到文本框中。
實現:
拿到這個需求的第一反應就是寫一個監聽來監聽鍵盤的顯示和隱藏來控制輸入框的顯示和隱藏,控制文本框中的內容。
所以我做了如下操作:
@Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { //old是改變前的左上右下坐標點值,沒有old的是改變后的左上右下坐標點值 //現在認為只要控件將Activity向上推的高度超過了1/3屏幕高,就認為軟鍵盤彈起 if(oldBottom != 0 && bottom != 0 &&(oldBottom - bottom > keyHeight)){ Toast.makeText(MainActivity.this, "監聽到軟鍵盤彈起...", Toast.LENGTH_SHORT).show(); }else if(oldBottom != 0 && bottom != 0 &&(bottom - oldBottom > keyHeight)){ Toast.makeText(MainActivity.this, "監聽到軟件盤關閉...", Toast.LENGTH_SHORT).show(); } }問題:
沒錯,這樣確實是能夠做到監聽軟鍵盤的彈出和隱藏,這一切都是因為之前設置了indowSoftInputMode=adjustResize,但是當全屏模式下是這個屬性是無效的,鍵盤彈出和隱藏并不會觸發onLayouChangeListener。
而項目中使用了SystemBarTintManager之后,Activity就變成了全屏模式所以我做了如下操作
//contentlayout是最外層布局mChildOfContent = contentlayout.getChildAt(0);mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { public void onGlobalLayout() { possiblyResizeChildOfContent(); }});private void possiblyResizeChildOfContent() { int usableHeightNow = computeUsableHeight(); if (usableHeightNow != usableHeightPrevious) { int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight(); int heightDifference = usableHeightSansKeyboard - usableHeightNow; if (heightDifference > (usableHeightSansKeyboard / 4)) { // 鍵盤彈出 } else { // 鍵盤收起 productInfo.setVisibility(View.GONE); productInfoEnd.setText(productInfo.getText().toString()); } mChildOfContent.requestLayout(); usableHeightPrevious = usableHeightNow; }}private int computeUsableHeight() { Rect r = new Rect(); mChildOfContent.getWindowVisibleDisplayFrame(r); return (r.bottom - r.top);}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答