美文网首页Android 成长笔记
Android 获取屏幕高度 获取输入法高度 示例

Android 获取屏幕高度 获取输入法高度 示例

作者: 赵者也 | 来源:发表于2017-03-18 10:22 被阅读85次

    本例用到的布局文件:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >
    
        <EditText
            android:id="@+id/editText"
            android:layout_width="300dp"
            android:layout_height="40dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="200dp"
            android:inputType="text"
            />
    
    </LinearLayout>
    

    主程序和用于获取屏幕高度和获取输入法高度的代码:

    package com.toby.personal.testlistview;
    
    import android.app.Activity;
    import android.graphics.Rect;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.ViewTreeObserver;
    import android.widget.EditText;
    
    public class MainActivity extends Activity {
    
        final private static String TAG = "Toby_Test";
        final private static int KeyboardHeightLimit = 200;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            final EditText editText = (EditText) findViewById(R.id.editText);
    
            checkKeyboardHeight(editText);
        }
    
        private void checkKeyboardHeight(final View chatRootLayout) {
            chatRootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    Rect r = new Rect();
    
                    chatRootLayout.getWindowVisibleDisplayFrame(r);
    
                    final int screenHeight = chatRootLayout.getRootView().getHeight();
                    Log.d(TAG, "screenHeight: " + screenHeight);
                    final int keyboardHeight = screenHeight - (r.bottom);
    
                    if (keyboardHeight > KeyboardHeightLimit) {
                        Log.d(TAG, "keyboardHeight: " + keyboardHeight);
                    }
                }
            });
        }
    
    }
    

    运行效果图:


    运行结果

    参考链接:http://stackoverflow.com/questions/29665435/how-to-get-the-height-of-android-keyboard

    相关文章

      网友评论

        本文标题:Android 获取屏幕高度 获取输入法高度 示例

        本文链接:https://www.haomeiwen.com/subject/cmrunttx.html