Android 解决键盘遮挡输入框
本文目录 点击直达
- 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回调中添加此功能即可
注意
因为使用通话的双通道麦克风实现了降噪,所以使用时可能声音较小,如果没有声音,请将声音调到最大,然后凑近麦克风吼两句"感谢博主,我会一键三连的"
最后我还有一句话要说
梧桐叶上三更雨,叶叶声声是别离。
周紫芝《鹧鸪天·一点残红欲尽时》