本文目錄 點擊直達
- Android 解決鍵盤遮擋輸入框
- 代碼實現
- 使用
- 注意
- 最后我還有一句話要說
- 梧桐葉上三更雨,葉葉聲聲是別離。
Android 解決鍵盤遮擋輸入框
在安卓中通常可以通過添加android:windowSoftInputMode="adjustResize|stateHidden"
的方式來讓鍵盤頂起布局,但是如果對狀態欄進行過著色隱藏等操作時,這個配置將不會生效,此時輸入框輸入時鍵盤仍然不會將布局抬起
經過一番搜索和驗證,可以使用AndroidBug5497Workaround來解決問題,但是現今此方案已無法完美適配底部導航欄的情況,所以我基于之前的方案進行了優化
代碼實現
將AdjustResizeHelper.kt類Copy進你的項目,需要注意的是這是kotlin語法
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Rect
import android.os.Build
import android.view.View
import android.view.WindowInsetsobject AdjustResizeHelper {fun supportAdjustResize(activity: Activity) {val decorView = activity.window.decorViewvar usableHeightPrevious = 0if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {decorView.setOnApplyWindowInsetsListener { v, insets ->val usableHeightNow = computeUsableHeight(decorView)if (usableHeightPrevious == usableHeightNow) {return@setOnApplyWindowInsetsListener insets}usableHeightPrevious = usableHeightNowval imeInsets = insets.getInsets(WindowInsets.Type.ime())val navigationBars = insets.getInsets(WindowInsets.Type.navigationBars())val keyboardHeight = imeInsets.bottom - navigationBars.bottomif (keyboardHeight > 0) {decorView.setPadding(0, 0, 0, keyboardHeight)} else {decorView.setPadding(0, 0, 0, 0)}v.onApplyWindowInsets(insets)}} else {decorView.viewTreeObserver.addOnGlobalLayoutListener {val usableHeightNow = computeUsableHeight(decorView)if (usableHeightPrevious == usableHeightNow) {return@addOnGlobalLayoutListener}usableHeightPrevious = usableHeightNowval rect = Rect()decorView.getWindowVisibleDisplayFrame(rect)val screenHeight = decorView.heightval heightDifference = screenHeight - rect.bottom - getNavigationBarHeight(activity)if (heightDifference > 100) { // 軟鍵盤彈出decorView.setPadding(0, 0, 0, heightDifference)} else { // 軟鍵盤隱藏decorView.setPadding(0, 0, 0, 0)}}}}@SuppressLint("InternalInsetResource")fun getNavigationBarHeight(context: Context): Int {val resources = context.resourcesval resourceId = resources.getIdentifier("navigation_bar_height","dimen","android")return if (resourceId > 0) {resources.getDimensionPixelSize(resourceId)} else 0}private fun computeUsableHeight(view: View): Int {val r = Rect()view.getWindowVisibleDisplayFrame(r)return (r.bottom - r.top)}
}
使用
使用起來很簡單,先在Activity的配置中添加android:windowSoftInputMode="adjustResize|stateHidden"
,然后如下圖在Activity的onCreate回調中添加此功能即可
注意
因為使用通話的雙通道麥克風實現了降噪,所以使用時可能聲音較小,如果沒有聲音,請將聲音調到最大,然后湊近麥克風吼兩句"感謝博主,我會一鍵三連的"
最后我還有一句話要說
梧桐葉上三更雨,葉葉聲聲是別離。
周紫芝《鷓鴣天·一點殘紅欲盡時》