Android 底部EditView输入时悬浮到软键盘上方

1. 修改 Activity 的 Manifest 配置

确保你的 Activity 在 AndroidManifest.xml 中有以下配置:

关键点:

  • adjustResize 是关键属性,使布局会为键盘腾出空间

  • stateHidden 可选,表示初始时不自动弹出键盘

2. 更新布局文件

使用 CoordinatorLayout 实现最可靠的效果:




    
     


 

        

        
    

3. 确保主题配置正确

在 styles.xml 中,确保 Activity 主题不是全屏模式:

4. 添加自动滚动功能(可选但推荐)

在代码中添加:

private fun setupKeyboardBehavior() {
    binding.root.viewTreeObserver.addOnGlobalLayoutListener {
        val rect = Rect()
        binding.root.getWindowVisibleDisplayFrame(rect)
        val screenHeight = binding.root.height
        val keypadHeight = screenHeight - rect.bottom
        
        if (keypadHeight > screenHeight * 0.15) { // 键盘显示
            binding.recyclerView.post {
                val lastPosition = (binding.recyclerView.adapter?.itemCount ?: 0) - 1
                if (lastPosition >= 0) {
                    binding.recyclerView.smoothScrollToPosition(lastPosition)
                }
            }
        }
    }
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    setupKeyboardBehavior()
    // ...其他初始化代码...
}

注意:enableEdgeToEdge失效问题

当布局使用enableEdgeToEdge(界面延申到通知栏的)时enableEdgeToEdge会失效

解决办法:

  public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        //解决enableEdgeToEdge与fitsSystemWindows= false时的冲突
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(android.R.id.content)) { view, insets ->
           val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
           //binding.content就是界面的最外层layout
           binding.content.updatePadding(top = -systemBars.top)
           insets
        }
}

 
 

你可能感兴趣的:(android)