Android 完美判断软键盘高度的方法

本文介绍了一种在Android中自定义ViewGroup来完美判断软键盘高度的方法。通过创建一个包含ScrollView的KeyboardLayout,并监听其尺寸变化,可以在软键盘显示时获取精确的高度。这种方法避免了机型和品牌差异带来的影响,确保了兼容性。
摘要由CSDN通过智能技术生成

首先自定义一个ViewGroup,可以继承已有的LinearLayout等

public class KeyboardLayout extends LinearLayout {
public KeyboardLayout(Context context) {
    super(context);
}

public KeyboardLayout(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
}

public KeyboardLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public KeyboardLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);

}

private int mLayoutHeight = 0;
private int mKeyboardHeight=0;


@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int h = resolveSize(0, heightMeasureSpec);
    mLayoutHeight = Math.max(mLayoutHeight, h);  //这里记录原始布局
    mKeyboardHeight=Math.max(mKeyboardHeight,Math.abs(mLayoutHeight -h));
    if(mKeyboardHeight>mLayoutHeight/5){
        存储这个软键盘高度
    }
    
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

}

在login页面定义大致如下

核心是KeyboardLayout里面必须有一个ScrollView布局

  <LinearLayout>
      <KeyboardLayout>
              <ScrollView>
                      <EditText/>
                 </ScrollView>
      </KeyboardLayout>
 </LinearLayout>

下面是我的实际代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/default_content_background"
    android:orientation="vertical"
    tools:context=".modules.login.views.LoginActivity">

    <com.maple.subway.modules.login.views.layouts.KeyboardLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:background="@color/default_font_color" />

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <LinearLayout
                android:layout_width="match_parent"
                android:lay
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值