Android底部控件随软键盘上移

很多时候我们会遇到这个问题,就是点击EditText弹出软键盘的时候会遮挡底部的Button,网上的解决方法一般都是设置WindowSoftInputMode和scrollview嵌套,这个局限性很多,而且有时候达不到我们想要的效果,下面我自定义了一个AutoKeyboardConstraintLayout,可以很小代码改动轻松解决这一问题。

闲话不多说,先看效果图:
图1.gif

图2.gif
用法很简单

第一种模式的用法(图1)

<!--用自定义的ConstraintLayout-->
<com.cfxc.autokeyboarddemo.autokeyboard.AutoKeyboardConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    <!--底部view上移后最高不能越过哪个view id-->
    app:aboveViewId="@+id/tv_register" 
    <!--移动模式. 不需要滚动的就用这个模式-->
    app:autoType="auto_translation" 
    <!-- 底部需要上移的view id集,中间用,隔开-->
    app:bottomViewIds="btn_login">

      <content
              ....
       />

    <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/btn_login"
            style="@style/largeButtonStyle"
            android:text="login"
            android:layout_marginBottom="30dp"
            android:background="@drawable/shape_white_radius_10"
            app:layout_constraintBottom_toBottomOf="parent" />

第二种模式的用法(图2)

<com.cfxc.autokeyboarddemo.autokeyboard.AutoKeyboardConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   <!--底部view上移后最高不能越过哪个view id-->
    app:aboveViewId="@+id/scroll_view"
   <!--移动模式. 需要滚动的就用这个模式-->
    app:autoType="auto_scroll"
   <!-- 底部需要上移的view id集,中间用,隔开-->
    app:bottomViewIds="btn_continue,btn_cancel">

    <!--需要滚动的内容用scroll view-->
    <androidx.core.widget.NestedScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginBottom="15dp"
        app:layout_constraintBottom_toTopOf="@+id/btn_continue"
        app:layout_constraintTop_toTopOf="parent">

       <content
        ....
       />

     </androidx.core.widget.NestedScrollView>

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btn_cancel"
        style="@style/largeButtonStyle"
        android:layout_marginBottom="20dp"
        android:background="@drawable/shape_white_radius_10"
        android:text="Cancel"
        app:layout_constraintBottom_toBottomOf="parent" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btn_continue"
        style="@style/largeButtonStyle"
        android:layout_marginBottom="10dp"
        android:background="@drawable/shape_white_radius_10"
        android:text="Continue"
        app:layout_constraintBottom_toTopOf="@id/btn_cancel" />

用法简单吧^ _ ^
主要就是封装自定义了AutoKeyboardConstraintLayout,用的时候只需要替换原布局的ConstraintLayout,xml中设置几个参数即可,代码不需要任何改动,不习惯用ConstraintLayout的童鞋,可以参照封装改成LinearLayout

下面是实现

定义下几个属性

<declare-styleable name="AutoKeyboardConstraintLayout">
        <attr name="bottomViewIds"/>
        <attr name="aboveViewId"/>
        <attr name="autoMargin"/>
        <attr name="autoType"/>
    </declare-styleable>
    <attr name="bottomViewIds" format="string" />
    <attr name="aboveViewId" format="reference" />
    <attr name="autoMargin" format="dimension" />
    <attr name="autoType" format="flags">
        <flag name="normal" value="0" />
        <flag name="auto_translation" value="1" />
        <flag name="auto_scroll" value="2" />
    </attr>

主要是这个AutoKeyboardConstraintLayout这个类

class AutoKeyboardConstraintLayout : ConstraintLayout {

    // not need move up
    private val NORMAL = 0

    // bottom view move up, the above view move up as need
    private val AUTO_TRANSLATION = 1

    /** bottom view move up, and change the scrollView height
     * Note: When used this type, that need to have a ScrollView or NestedScrollView or RecyclerView in the layout, and set the above view's id is it's id
     **/
    private val AUTO_SCROLL = 2

    // the id of the views that need move up
    private var bottomViewIds = arrayListOf<Int>()

    //the id of the view above of the bottom view
    private var aboveViewId: Int = NO_ID
    private var onGlobalLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null
    private var rootViewVisibleHeight: Int = 0
    private var rootViewHeight: Int = 0

    // This margin is the height from the keyboard when the bottom view moves up
    private var viewMargin: Float = 10f

    //the type of that need move up
    private var autoType = NORMAL
    private val animatorDuration = 100L
    private var toolbarHeight: Int = 0

    constructor(context: Context) : super(context) {
        initViews(null)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initViews(attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initViews(attrs)
    }

    @SuppressLint("CustomViewStyleable")
    private fun initViews(attrs: AttributeSet?) {
        attrs?.let {
            val typedArray = context.obtainStyledAttributes(attrs, R.styleable.AutoKeyboardConstraintLayout)
            val idStrings = typedArray.getString(R.styleable.AutoKeyboardConstraintLayout_bottomViewIds)
            setBottomViewID(idStrings)
            aboveViewId = typedArray.getResourceId(R.styleable.AutoKeyboardConstraintLayout_aboveViewId, NO_ID)
            viewMargin = typedArray.getDimension(R.styleable.AutoKeyboardConstraintLayout_autoMargin, 10f)
            autoType = typedArray.getInt(R.styleable.AutoKeyboardConstraintLayout_autoType, NORMAL)
            typedArray.recycle()
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        if (autoType != NORMAL) {
            onGlobalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
                //Gets the size of the current root view displayed on the screen
                val r = Rect()
                getWindowVisibleDisplayFrame(r)

                val visibleHeight = r.height()
                rootViewHeight = rootViewHeight.coerceAtLeast(visibleHeight)
                if (rootViewVisibleHeight == 0) {
                    rootViewVisibleHeight = visibleHeight
                    return@OnGlobalLayoutListener
                }
                //The display height of the root view doesn't change
                if (rootViewVisibleHeight == visibleHeight) {
                    return@OnGlobalLayoutListener
                }

                //The display height of the root view has been reduced to over 200 and can be viewed as a soft keyboard display
                if (rootViewHeight - visibleHeight > 200) {
                    val keyboardHeight = rootViewHeight - visibleHeight

                    changeLayout(keyboardHeight)
                    rootViewVisibleHeight = visibleHeight
                    return@OnGlobalLayoutListener
                }

                //The root view shows a larger height than 200, which can be seen as a soft keyboard hidden
                if (visibleHeight - rootViewVisibleHeight > 200) {
                    //keyboard hide
                    restoreView()
                    rootViewVisibleHeight = visibleHeight
                    return@OnGlobalLayoutListener
                }
            }
            viewTreeObserver?.addOnGlobalLayoutListener(onGlobalLayoutListener)
        }
    }

    private fun changeLayout(keyboardHeight: Int) {
        when (autoType) {
            AUTO_TRANSLATION, AUTO_SCROLL -> translationBottomView(keyboardHeight)
        }
    }

    private fun translationBottomView(keyboardHeight: Int) {
        //this is to support toolbar
        val parentView = getRootView(parent)
        // parentView is MainActivity root view
        parentView?.let {drawerLayout->
            // the height of the toolbar is the view in the MainActivity layout
            if (drawerLayout is ViewGroup){
                val toolbarParent = drawerLayout[0]
                if(toolbarParent is ViewGroup && toolbarParent[0] is Toolbar&& toolbarParent[0].isShown){
                    toolbarHeight = toolbarParent[0].height
                }
            }
        }
        var translationHeight = 0f
        var isNeedBottomTranslation = false
        // the lowest view of the bottom views
        var lowestView: View? = null
        // the highest view of the bottom views
        var highestView: View? = null
        var needHeight = 0f
        for (item in bottomViewIds) {
            val bottomView = getViewById(item)
            bottomView?.let {
                if (bottomView.visibility == View.VISIBLE) {
                    lowestView = if (bottomView.bottom > lowestView?.bottom ?: 0) bottomView else lowestView
                    highestView = if (bottomView.top < highestView?.top ?: rootViewHeight) bottomView else highestView
                }
            }
        }

        val aboveView = if (aboveViewId == NO_ID) null else getViewById(aboveViewId)
        var aboveViewBottom = 0
        aboveView?.apply {
            aboveViewBottom = bottom
        }

        lowestView?.let { lowest ->
            if (this.height - lowest.bottom >= keyboardHeight) return
            highestView?.let { highest ->
                val bottomViewsHeight = lowest.bottom - highest.top
                if (aboveViewBottom == 0
                        || keyboardHeight + bottomViewsHeight + dip2px(viewMargin * 2) < this.height - aboveViewBottom
                        || autoType == AUTO_SCROLL) {
                    needHeight = keyboardHeight - (this.height - lowest.bottom) + dip2px(viewMargin) - getNavigationBarHeight()
                    translationHeight = 0f
                    isNeedBottomTranslation = true
                } else {
                    needHeight = keyboardHeight + aboveViewBottom + bottomViewsHeight + dip2px(viewMargin * 2) - getNavigationBarHeight()
                    translationHeight = this.height - needHeight
                    isNeedBottomTranslation = lowest.bottom + translationHeight > this.height - keyboardHeight - dip2px(viewMargin)
                }
            }
        }

        if (isNeedBottomTranslation)
            for (item in bottomViewIds) {
                val bottomView = getViewById(item)
                if (bottomView.visibility == View.VISIBLE)
                    bottomView.animate().setDuration(animatorDuration).translationY(this.height - (lowestView?.bottom
                            ?: 0) - keyboardHeight - dip2px(viewMargin) - translationHeight + getNavigationBarHeight()).start()
            }
        if (autoType == AUTO_TRANSLATION && aboveViewBottom > 0 && needHeight > this.height) {
            this.animate().setDuration(animatorDuration).translationY(translationHeight).start()
        }
        if (autoType == AUTO_SCROLL) {
            aboveView?.let {
                if (aboveView is ScrollView || aboveView is NestedScrollView || aboveView is RecyclerView) {
                    val layoutParams = aboveView.layoutParams
                    (layoutParams as LayoutParams).bottomMargin = (needHeight + dip2px(viewMargin)).toInt()
                    aboveView.layoutParams = layoutParams
                }
            }
        }
    }

    private fun getRootView(viewParent: ViewParent?): ViewParent? {
        if (viewParent != null) {
            if (viewParent is DrawerLayout) {
                return viewParent
            } else {
               return getRootView(viewParent.parent)
            }
        } else {
            return null
        }
    }

    private fun restoreView() {
        when (autoType) {
            AUTO_TRANSLATION, AUTO_SCROLL -> restoreTranslation()
        }
    }

    private fun restoreTranslation() {
        for (item in bottomViewIds) {
            val bottomView = getViewById(item)
            bottomView?.let {
                this.animate().setDuration(animatorDuration).translationY(0f)
                it.animate().setDuration(animatorDuration).translationY(0f)
            }
        }
        if (autoType == AUTO_SCROLL) {
            val aboveView = if (aboveViewId == NO_ID) null else getViewById(aboveViewId)
            aboveView?.let {
                if (aboveView is ScrollView || aboveView is NestedScrollView || aboveView is RecyclerView) {
                    val layoutParams = aboveView.layoutParams
                    (layoutParams as LayoutParams).bottomMargin = 0
                    aboveView.layoutParams = layoutParams
                }
            }
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        toolbarHeight = 0
        if (autoType != NORMAL)
            viewTreeObserver?.removeOnGlobalLayoutListener(onGlobalLayoutListener)
    }

    private fun setBottomViewID(idStrings: String?) {
        idStrings?.let {
            val idLists = it.split(",")
            for (item in idLists) {
                addID(item)
            }
        }
    }

    private fun addID(idString: String) {
        val idStr = idString.trim()
        var tag = 0
        try {
            val res: Class<*> = id::class.java
            val field = res.getField(idStr)
            tag = field.getInt(null as Any?)
        } catch (var5: Exception) {
        }
        if (tag == 0) {
            tag = context.resources.getIdentifier(idStr, "id", context.packageName)
        }
        if (tag == 0) {
            val constraintLayout = this.parent as ConstraintLayout
            val value = constraintLayout.getDesignInformation(0, idStr)
            if (value != null && value is Int) {
                tag = value
            }
        }
        if (tag != 0) {
            bottomViewIds.add(tag)
        } else {
            Log.w("AutoKeyboardLayout", "Could not find id of \"$idStr\"")
        }
    }

    private fun dip2px(dpValue: Float): Float {
        val scale = context.resources.displayMetrics.density
        return dpValue * scale + 0.5f
    }

    // This is to support the navigation bar show hide
    private fun getNavigationBarHeight(): Int {
        return rootViewHeight - this.height - toolbarHeight
    }
}

注释是英文的,因为是在做公司项目的时候写的这个控件,公司项目注释要求是英文的,也懒得改中文了( ̄∇ ̄)

附上demo地址:https://github.com/fengpeihao/AutoKeyboardDemo

第一次写文章,写的很简单,主要是为了记录下方便以后用到查看

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容