1. 程式人生 > >佈局在輸入框懸浮

佈局在輸入框懸浮

知識拓展

android:windowSoftInputMode:設定窗體軟鍵盤的互動模式。

1. stateUnspecified
當設定屬性為stateUnspecified的時候,系統是預設不彈出軟鍵盤的。可是當有獲得焦點的輸入框的介面有滾動的需求的時候,會自己主動彈出軟鍵盤。
2. stateUnchanged
就是說,當前介面的軟鍵盤狀態,取決於上一個介面的軟鍵盤狀態。舉個樣例,假如當前介面鍵盤是隱藏的,那麼跳轉之後的介面,軟鍵盤也是隱藏的;假設當前介面是顯示的,那麼跳轉之後的介面,軟鍵盤也是顯示狀態。
3. stateHidden
假設我們設定了這個屬性,那麼鍵盤狀態一定是隱藏的,無論上個介面什麼狀態。也無論當前介面有沒有輸入的需求,反正就是不顯示。因此,我們能夠設定這個屬性,來控制軟鍵盤不自己主動的彈出。
4. stateAlwaysHidden


這個屬性也能夠讓軟鍵盤隱藏
5. stateVisible
設定為這個屬性,能夠將軟鍵盤召喚出來,即使在介面上沒有輸入框的情況下也能夠強制召喚出來。
6. stateAlwaysVisible
這個屬性也是能夠將鍵盤召喚出來,可是與stateVisible屬性有小小的不同之處。舉個樣例,當我們設定為stateVisible屬性,假設當前的介面鍵盤是顯示的,當我們點選button跳轉到下個介面的時候,軟鍵盤會由於輸入框失去焦點而隱藏起來,當我們再次回到當前介面的時候,鍵盤這個時候是隱藏的。可是假設我們設定為stateAlwaysVisible,我們跳轉到下個介面,軟鍵盤還是隱藏的,可是當我們再次回來的時候。軟鍵盤是會顯示出來的。
7. adjustResize

這個屬性表示Activity的主窗體總是會被調整大小,從而保證軟鍵盤顯示空間。
8. adjustPan
當前視窗的內容將自動移動以便當前焦點從不被鍵盤覆蓋和使用者能總是看到輸入內容的部分
9. adjustUnspecified
預設設定,通常由系統自行決定是隱藏還是顯示

效果圖:
在這裡插入圖片描述

作用:宣告getGlobalLayoutListener()方法,傳入你的手機螢幕與指定的控制元件。ViewTreeObserver會監聽你的螢幕,當軟鍵盤彈出時,螢幕可見高度(r.bottom)變小。計算螢幕高度與r.bottom的差值,即為軟鍵盤的高度(diff)。將指定控制元件的paddingBottom設為diff,就實現了“自定義輸入框位於軟鍵盤上方”。同理,當軟鍵盤消失時,paddingBottom設為0,輸入框自動落回底部。

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        View decorView = getWindow().getDecorView();
        View contentView = findViewById(Window.ID_ANDROID_CONTENT);
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(getGlobalLayoutListener(decorView, contentView));
    }
     private ViewTreeObserver.OnGlobalLayoutListener getGlobalLayoutListener(final View decorView, final View contentView) {
         return new ViewTreeObserver.OnGlobalLayoutListener() {
             @Override
             public void onGlobalLayout() {
                 Rect r = new Rect();
                 //用來獲取當前視窗可視區域的大小
                 decorView.getWindowVisibleDisplayFrame(r);
                 int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
                 //軟鍵盤的高度
                 int diff = height - r.bottom;
                 if (diff != 0) {
                     if (contentView.getPaddingBottom() != diff) {
                         contentView.setPadding(0, 0, 0, diff);
                     }
                 } else {
                     if (contentView.getPaddingBottom() != 0) {
                         contentView.setPadding(0, 0, 0, 0);
                     }
                 }
             }
         };
     }
}

decorView.getViewTreeObserver().addOnGlobalLayoutListener
4.4機型適配問題