Android软键盘问题总结

2021-09-15  本文已影响0人  独自闯天涯的码农

Android软键盘聊天页面设置
1、activity的在manifest中设置键盘模式

android:windowSoftInputMode="stateHidden|adjustPan"

2、在Activity中设置

mContext.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

3、监听RecyclerView高度变化并刷新页面

//用于监听RecyclerView高度的变化,从而刷新列表
        recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(OnGlobalLayoutListener {
            val height: Int = recyclerView.getHeight()
            if (recyclerViewLastHeight == 0) {
                recyclerViewLastHeight = height;
            }
            if (recyclerViewLastHeight != height) {
                //RecyclerView高度发生变化,刷新页面
                if (listData != null) {
                    seekToPosition(listData.size - 1);
                }
            }
            recyclerViewLastHeight = height;
        })

/**
     * 移动到指定位置
     * @param position
     */
    private fun seekToPosition(position: Int) {
        var position = position
        if (position < 0) {
            position = 0
        }
        val manager: RecyclerView.LayoutManager? = recyclerView.getLayoutManager()
        if (manager is LinearLayoutManager) {
            val finalPosition = position
            recyclerView.post(Runnable { setMoveAnimation(manager, finalPosition) })
        }
    }

    private fun setMoveAnimation(manager: RecyclerView.LayoutManager, position: Int) {
        val animator = ValueAnimator.ofInt(-200, 0)
        animator.addUpdateListener { animation ->
            val value = animation.animatedValue as Int
            (manager as LinearLayoutManager).scrollToPositionWithOffset(position, value)
        }
        animator.duration = 500
        animator.start()
    }

4、监听根布局高度变化并刷新页面(为了解决透明导航栏状态栏后与软键盘产生冲突的问题)
参考透明状态栏键盘冲突

val decorView = window.decorView
decorView.viewTreeObserver.addOnGlobalLayoutListener {
  val rect = Rect()
  decorView.getWindowVisibleDisplayFrame(rect)
  val screenHeight = decorView.rootView.height
  val heightDiff = screenHeight -rect.bottom
  val layoutParams = mBinding.clRoot.layoutParams as ViewGroup.MarginLayoutParams
  layoutParams.setMargins(0,0,0,heightDiff)
  mBinding.clRoot.requestLayout()
}

5、还有另外一种设置软键盘上方显示输入框的方法:
通过创建一个带EditText的Dialog

上一篇下一篇

猜你喜欢

热点阅读