android 获取键盘高度
时间: 2023-10-18 13:19:39 浏览: 35
在 Android 中,可以使用以下代码获取键盘的高度:
1. 在布局文件中添加以下代码:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type here..." />
</RelativeLayout>
```
2. 在 Activity 中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private View mContentView;
private EditText mEditText;
private int mKeyboardHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContentView = findViewById(R.id.activity_main);
mEditText = findViewById(R.id.edit_text);
mContentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
mContentView.getWindowVisibleDisplayFrame(r);
int screenHeight = mContentView.getRootView().getHeight();
int keyboardHeight = screenHeight - r.bottom;
if (keyboardHeight > 100) {
mKeyboardHeight = keyboardHeight;
}
}
});
}
}
```
在上面的代码中,我们使用 `ViewTreeObserver` 监听 `mContentView` 的布局变化。当键盘弹出或隐藏时,`onGlobalLayout` 方法会被触发。我们可以通过计算 `mContentView` 的高度和窗口可见区域的底部之差来获取键盘的高度。如果键盘高度大于 100,我们就认为键盘已经弹出,将键盘高度保存到 `mKeyboardHeight` 变量中。