Android輸入法軟鍵盤懸浮,最多見的一種方法是經過給ViewTreeObserver添加ViewTreeObserver.OnGlobalLayoutListener當全局佈局完成時或視圖樹中視圖的可見性發生變化時回調onGlobalLayout方法,在onGlobalLayout方法中獲取當前窗口的區域,獲取區域高度若是超過屏幕的五分之一通常認爲是軟鍵盤處於顯示狀態,區域高度即爲輸入法軟鍵盤高度,經過此高度動態調整view的高度,達到輸入框懸浮於軟鍵盤上方的效果,代碼以下:java
ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { int mScreenHeight = 0; int mKeyboardHeight = 0; @Override public void onGlobalLayout() { Rect rect = new Rect(); // 測量當前窗口的顯示區域 ((Activity)getContext()).getWindow().getDecorView() .getWindowVisibleDisplayFrame(rect); if(mScreenHeight <= 0){ mScreenHeight = ((WindowManager) getContext() .getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay().getHeight(); } //計算出軟鍵盤的高度 int keyboardHeight = mScreenHeight - rect.bottom; //若是keyboardHeight大於屏幕的五分之一, // 此時keyboardHeight有效,反之就是軟鍵盤已經關閉了。 if (Math.abs(keyboardHeight) > mScreenHeight / 5) { mKeyboardHeight = keyboardHeight; } } }
還有一種方式是給Activity設置 Android:windowSoftInputMode="stateVisible|adjustResize",可是這種方法不是很靈活,通常解決不了產品的需求。android
<activity android:name=".activity.xxx" Android:windowSoftInputMode="stateVisible|adjustResize"/>
先來張效果圖git
1.自定義一個activity themegithub
<style name="NoTitleDialogTheme" parent="android:style/Theme.Dialog"> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:windowNoTitle">true</item> <item name="android:windowCloseOnTouchOutside">false</item> </style>
2.在AndroidManifest.xml中設置app
<activity android:name=".FloatEditorActivity" android:windowSoftInputMode="stateAlwaysVisible" android:theme="@style/NoTitleDialogTheme"/>
3.在Activity中調整window的重力方向ide
public class FloatEditorActivity extends Activity implements View.OnClickListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.id.editorlayout); getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); getWindow().setGravity(Gravity.BOTTOM); } }
就這樣很是簡單的實現了浮動編輯框的效果,所有源碼已上傳到github並作了很好的的封裝,只需實現你的需求佈局便可,裏面也有完整的用法實例。佈局