如何检测软件键盘在Android设备上是否可见?


249

Android中是否有一种方法可以检测屏幕上是否显示软件(又名“软”)键盘?



1
在某些情况下(如果已安装第三方键盘),解决方案是检查全局通知,因为当键盘打开时,系统会显示“更改键盘”的通知
教授

2
近8年了,仍然没有任何可靠的解决方案,哦,如果他们引入一个解决方案,无论如何,它都将用于API> 30,所以没关系...
M.kazem Akhgary

Answers:



276

这对我有用。也许这始终是所有版本的最佳方法。

设置键盘可见性的属性并观察此更改是有效的,因为onGlobalLayout方法会多次调用。另外,检查设备的旋转情况也不错,而windowSoftInputMode不是adjustNothing

boolean isKeyboardShowing = false;
void onKeyboardVisibilityChanged(boolean opened) {
    print("keyboard " + opened);
}

// ContentView is the root view of the layout of this activity/fragment    
contentView.getViewTreeObserver().addOnGlobalLayoutListener(
    new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {

        Rect r = new Rect();
        contentView.getWindowVisibleDisplayFrame(r);
        int screenHeight = contentView.getRootView().getHeight();

        // r.bottom is the position above soft keypad or device button.
        // if keypad is shown, the r.bottom is smaller than that before.
        int keypadHeight = screenHeight - r.bottom;

        Log.d(TAG, "keypadHeight = " + keypadHeight);

        if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is perhaps enough to determine keypad height.
            // keyboard is opened
            if (!isKeyboardShowing) {
                isKeyboardShowing = true
                onKeyboardVisibilityChanged(true)
            }
        }
        else {
            // keyboard is closed
            if (isKeyboardShowing) {
                isKeyboardShowing = false
                onKeyboardVisibilityChanged(false)
            }
        }
    }
});


1
将其放在utils类中并传递活动-现在对整个应用程序很有用。
贾斯汀

2
contentView声明在哪里?
学徒制

1
@ Code-Apprentice在活动/片段中,您希望响应软键盘更改。ContentView是此活动/片段的布局的根视图。
airowe

1
为我工作在Android 6和7
V.March

71

试试这个:

InputMethodManager imm = (InputMethodManager) getActivity()
            .getSystemService(Context.INPUT_METHOD_SERVICE);

    if (imm.isAcceptingText()) {
        writeToLog("Software Keyboard was shown");
    } else {
        writeToLog("Software Keyboard was not shown");
    }

9
这对我不起作用。即使在从不显示键盘或显示键盘然后将其关闭的情况下,显示的键盘分支也会触发。
彼得·阿杰泰

30
它总是返回true。
shivang Trivedi 2013年

1
是的,它总是返回true。
莱昂佩尔蒂埃

错误。这总是返回true
Gaurav Arora

178
这是可悲的是,Android框架缺乏,更糟的是,不一致的在这方面。这应该是超级简单的。
Vicky Chijwani,2015年

57

我创建了一个可用于此目的的简单类:https : //github.com/ravindu1024/android-keyboardlistener。只需将其复制到您的项目中并按以下方式使用:

KeyboardUtils.addKeyboardToggleListener(this, new KeyboardUtils.SoftKeyboardToggleListener()
{
    @Override
    public void onToggleSoftKeyboard(boolean isVisible)
    {
        Log.d("keyboard", "keyboard visible: "+isVisible);
    }
});

我必须在代码提示中的哪个位置放这个?我将其放在一个活动中,但是它不会检测到任何键盘的出现或消失。
Toom

好吧,您可以将其放在活动中的任何位置。只需在setContentView()调用之后将其放在onCreate()方法中,就应该获得回调。顺便说一句,您在尝试什么设备?
ravindu1024 '16

我检查了@MaulikDodia,它在片段中工作正常。像这样设置:KeyboardUtils.addKeyboardToggleListener(getActivity(),this); 它应该工作。您正在尝试什么设备?
ravindu1024

我正在尝试使用Moto-G3设备。@ ravindu1024
Maulik Dodia

感谢您提供此代码段,我有一个问题,删除监听程序需要此代码吗?
Pratik Butani

28

好简单

1.在您的根视图上放置id

rootView在这种情况下只是一个指向我的根视图的视图relative layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/addresses_confirm_root_view"
                android:background="@color/WHITE_CLR">

2.在活动中初始化您的根视图:

RelativeLayout rootView = (RelativeLayout) findViewById(R.id.addresses_confirm_root_view);

3.通过使用检测键盘是打开还是关闭 getViewTreeObserver()

    rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightDiff = rootView.getRootView().getHeight() - rootView.getHeight();

                if (heightDiff > 100) { 
                    Log.e("MyActivity", "keyboard opened");
                } else { 
                    Log.e("MyActivity", "keyboard closed");
                }
            }
        });

15
嗨,老兄,你能告诉我这魔术100的来源吗?为什么不选择101或99?谢谢
Karoly

@Karoly我认为可能是and 1。不管。只有这必须小于键盘的实际长度
Vlad17年

@Karoly,基本上,他正在将窗口大小与活动的根视图大小进行比较。软键盘的外观不会影响主窗口的大小。所以你仍然可以降低100的值
MR5

魔幻数字取决于您的topbar布局等。因此它与您的应用程序有关。我在我的一个中用了400。
Morten Holmgaard,

请记住,onGlobalLayout在每一帧都被调用,因此请确保您在其中不要做繁琐的事情。
Akshay Gaonkar,

8

我以此为基础:http : //www.ninthavenue.com.au/how-to-check-if-the-software-keyboard-is-shown-in-android

/**
* To capture the result of IMM hide/show soft keyboard
*/
public class IMMResult extends ResultReceiver {
     public int result = -1;
     public IMMResult() {
         super(null);
}

@Override 
public void onReceiveResult(int r, Bundle data) {
    result = r;
}

// poll result value for up to 500 milliseconds
public int getResult() {
    try {
        int sleep = 0;
        while (result == -1 && sleep < 500) {
            Thread.sleep(100);
            sleep += 100;
        }
    } catch (InterruptedException e) {
        Log.e("IMMResult", e.getMessage());
    }
    return result;
}
}

然后写了这个方法:

public boolean isSoftKeyboardShown(InputMethodManager imm, View v) {

    IMMResult result = new IMMResult();
    int res;

    imm.showSoftInput(v, 0, result);

    // if keyboard doesn't change, handle the keypress
    res = result.getResult();
    if (res == InputMethodManager.RESULT_UNCHANGED_SHOWN ||
            res == InputMethodManager.RESULT_UNCHANGED_HIDDEN) {

        return true;
    }
    else
        return false;

}

然后,您可以使用它来测试可能已打开软键盘的所有字段(EditText,AutoCompleteTextView等):

    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    if(isSoftKeyboardShown(imm, editText1) | isSoftKeyboardShown(imm, autocompletetextview1))
        //close the softkeyboard
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

绝对不是理想的解决方案,但是它可以完成工作。


2
这可行。如果您以singelton的方式实现,则可以将所有焦点焦点更改应用到edittext上,并拥有一个全局键盘侦听器
Rarw

@depperm getActivity()特定于片段,请尝试使用YourActivityName.this。参见:stackoverflow.com/questions/14480129/...
克里斯托弗·哈克尔


6

您可以参考此答案-https: //stackoverflow.com/a/24105062/3629912

每次都对我有用。

adb shell dumpsys window InputMethod | grep "mHasSurface"

如果软件键盘可见,它将返回true。


10
这仅在开发期间有用,而不是在应用程序中使用的解决方案。(用户不会运行adb。)
ToolmakerSteve

5

因此,在长时间使用AccessibilityServices,窗口插图,屏幕高度检测等之后,我想我找到了一种方法。

免责声明:它在Android中使用隐藏方法,这意味着可能不一致。但是,在我的测试中,它似乎有效。

该方法是InputMethodManager#getInputMethodWindowVisibleHeight(),并且从Lollipop(5.0)开始就存在。

调用将返回当前键盘的高度(以像素为单位)。从理论上讲,键盘的高度不应为0像素,因此我做了一个简单的高度检查(在Kotlin中):

val imm by lazy { context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager }
if (imm.inputMethodWindowVisibleHeight > 0) {
    //keyboard is shown
else {
    //keyboard is hidden
}

当我调用隐藏方法时,我使用Android Hidden API来避免反射(我为我开发的应用程序做了很多事情,大多数是hacky / tuner应用程序),但是反射也应该可行:

val imm by lazy { context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager }
val windowHeightMethod = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight")
val height = windowHeightMethod.invoke(imm) as Int
//use the height val in your logic

惊人的反射使用
kaustubhpatange

4

对于我所需的需求来说,这要简​​单得多。希望这会有所帮助:

在MainActivity上:

public void dismissKeyboard(){
    InputMethodManager imm =(InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(mSearchBox.getWindowToken(), 0);
    mKeyboardStatus = false;
}

public void showKeyboard(){
    InputMethodManager imm =(InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    mKeyboardStatus = true;
}

private boolean isKeyboardActive(){
    return mKeyboardStatus;
}

mKeyboardStatus的默认基本布尔值将初始化为false

然后按如下所示检查值,并在必要时执行操作:

 mSearchBox.requestFocus();
    if(!isKeyboardActive()){
        showKeyboard();
    }else{
        dismissKeyboard();
    }

4

如果您需要检查键盘状态,这应该可以工作:

fun Activity.isKeyboardOpened(): Boolean {
    val r = Rect()

    val activityRoot = getActivityRoot()
    val visibleThreshold = dip(UiUtils.KEYBOARD_VISIBLE_THRESHOLD_DP)

    activityRoot.getWindowVisibleDisplayFrame(r)

    val heightDiff = activityRoot.rootView.height - r.height()

    return heightDiff > visibleThreshold;
}

fun Activity.getActivityRoot(): View {
    return (findViewById<ViewGroup>(android.R.id.content)).getChildAt(0);
}

其中UiUtils.KEYBOARD_VISIBLE_THRESHOLD_DP= 100和dip()是转换dpToPx的anko函数:

fun dip(value: Int): Int {
    return (value * Resources.getSystem().displayMetrics.density).toInt()
}

3

我通过设置GlobalLayoutListener来做到这一点,如下所示:

final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
        new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightView = activityRootView.getHeight();
                int widthView = activityRootView.getWidth();
                if (1.0 * widthView / heightView > 3) {
                    //Make changes for Keyboard not visible
                } else {
                    //Make changes for keyboard visible
                }
            }
        });

这将经常被称为
Denis Kniazhev 2014年

在什么情况下,这与@BrownsooHan的答案会有所不同?我正在寻找一种显示可替代其他应用程序以摆脱键盘干扰的应用程序的方式。
埃文·朗格瓦伊斯

他的回答与我的回答基本相同,只是我比他早几个月才得到我的回答,他的投票更多。
PearsonArtPhoto

3

尝试这段代码,如果显示了KeyboardShown,那么它确实起作用,然后此函数返回true值...。

private final String TAG = "TextEditor";
private TextView mTextEditor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_editor);
    mTextEditor = (TextView) findViewById(R.id.text_editor);
    mTextEditor.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            isKeyboardShown(mTextEditor.getRootView());
        }
    });
}

private boolean isKeyboardShown(View rootView) {
    /* 128dp = 32dp * 4, minimum button height 32dp and generic 4 rows soft keyboard */
    final int SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD = 128;

    Rect r = new Rect();
    rootView.getWindowVisibleDisplayFrame(r);
    DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
    /* heightDiff = rootView height - status bar height (r.top) - visible frame height (r.bottom - r.top) */
    int heightDiff = rootView.getBottom() - r.bottom;
    /* Threshold size: dp to pixels, multiply with display density */
    boolean isKeyboardShown = heightDiff > SOFT_KEYBOARD_HEIGHT_DP_THRESHOLD * dm.density;

    Log.d(TAG, "isKeyboardShown ? " + isKeyboardShown + ", heightDiff:" + heightDiff + ", density:" + dm.density
            + "root view height:" + rootView.getHeight() + ", rect:" + r);

    return isKeyboardShown;
}

如果isKeyboardShown未显示,则继续调用自身。
Mandeep Singh

2

就我而言,我只有一个人EditText可以管理布局,因此我提出了这个解决方案。它运作良好,基本上是一个自定义项EditText,可以在焦点发生变化或按下后退/完成按钮时侦听焦点并发送本地广播。为了工作,您需要View使用android:focusable="true"和在布局中放置一个虚拟对象,android:focusableInTouchMode="true"因为调用时clearFocus()焦点将重新分配给第一个可聚焦视图。虚拟视图的示例:

<View
android:layout_width="1dp"
android:layout_height="1dp"
android:focusable="true"
android:focusableInTouchMode="true"/>

其他资讯

用于检测布局更改差异的解决方案效果不佳,因为它很大程度上取决于屏幕密度,因为在某些设备中100px可能很大,而在其他某些设备中则没有,您可能会得到误报。另外,不同的供应商具有不同的键盘。


1

在Android中,您可以通过ADB Shell进行检测。我编写并使用了这种方法:

{
        JSch jsch = new JSch();
        try {
            Session session = jsch.getSession("<userName>", "<IP>", 22);
            session.setPassword("<Password>");
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

            ChannelExec channel = (ChannelExec)session.openChannel("exec");
            BufferedReader in = new BufferedReader(new    
            InputStreamReader(channel.getInputStream()));
            channel.setCommand("C:/Android/android-sdk/platform-tools/adb shell dumpsys window 
            InputMethod | findstr \"mHasSurface\"");
            channel.connect();

            String msg = null;
            String msg2 = " mHasSurface=true";

            while ((msg = in.readLine()) != null) {
                Boolean isContain = msg.contains(msg2);
                log.info(isContain);
                if (isContain){
                    log.info("Hiding keyboard...");
                    driver.hideKeyboard();
                }
                else {
                    log.info("No need to hide keyboard.");
                }
            }

            channel.disconnect();
            session.disconnect();

        } catch (JSchException | IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

1
您能否通过一个更具体的示例(包括所有导入内容和一个有效示例)来改善此答案?
User3 2015年

1
final View activityRootView = findViewById(R.id.rootlayout);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

            Rect r = new Rect();
            activityRootView.getWindowVisibleDisplayFrame(r);

            int screenHeight = activityRootView.getRootView().getHeight();
            Log.e("screenHeight", String.valueOf(screenHeight));
            int heightDiff = screenHeight - (r.bottom - r.top);
            Log.e("heightDiff", String.valueOf(heightDiff));
            boolean visible = heightDiff > screenHeight / 3;
            Log.e("visible", String.valueOf(visible));
            if (visible) {
                Toast.makeText(LabRegister.this, "I am here 1", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(LabRegister.this, "I am here 2", Toast.LENGTH_SHORT).show();
            }
        }
});

1

@iWantScala的答案很好,但对我不起作用
rootView.getRootView().getHeight()总是具有相同的价值

一种方法是定义两个变量

private int maxRootViewHeight = 0;
private int currentRootViewHeight = 0;

添加全局侦听器

rootView.getViewTreeObserver()
    .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            currentRootViewHeight = rootView.getHeight();
            if (currentRootViewHeight > maxRootViewHeight) {
                maxRootViewHeight = currentRootViewHeight;
            }
        }
    });

然后检查

if (currentRootViewHeight >= maxRootViewHeight) {
    // Keyboard is hidden
} else {
    // Keyboard is shown
}

工作良好


1

现在终于有了直接的途径,从基于Kotlin的Android R开始。

 val imeInsets = view.rootWindowInsets.getInsets(Type.ime()) 
    if (imeInsets.isVisible) { 
     //Ime is visible
     //Lets move our view by the height of the IME
     view.translationX = imeInsets.bottom }

0

我有一个类似的问题。我需要对屏幕上的Enter键(隐藏键盘)做出反应。在这种情况下,您可以订阅打开了键盘的文本视图的OnEditorAction-如果您有多个可编辑的框,请订阅所有这些。

在“活动”中,您可以完全控制键盘,因此,如果您侦听所有打开和关闭事件,无论您是否打开键盘,都不会遇到任何问题。


对我不起作用。我仅在OnEditorAction中收到Enter键。
3c71

0

有一个直接的方法可以找到答案。而且,它不需要更改布局。
因此,它也可以在沉浸式全屏模式下工作。
但是,不幸的是,它不适用于所有设备。因此,您必须使用您的设备进行测试。

诀窍是您尝试隐藏或显示软键盘并捕获该尝试的结果。
如果工作正常,则说明键盘没有真正显示或隐藏。我们只是要求状态。

为了保持最新状态,您只需使用Handler即可重复此操作,例如每200毫秒重复一次。

下面的实现仅进行一次检查。
如果进行多次检查,则应启用所有(_keyboardVisible)测试。

public interface OnKeyboardShowHide
{
    void    onShowKeyboard( Object param );
    void    onHideKeyboard( Object param );
}

private static Handler      _keyboardHandler    = new Handler();
private boolean             _keyboardVisible    = false;
private OnKeyboardShowHide  _keyboardCallback;
private Object              _keyboardCallbackParam;

public void start( OnKeyboardShowHide callback, Object callbackParam )
{
    _keyboardCallback      = callback;
    _keyboardCallbackParam = callbackParam;
    //
    View view = getCurrentFocus();
    if (view != null)
    {
        InputMethodManager imm = (InputMethodManager) getSystemService( Activity.INPUT_METHOD_SERVICE );
        imm.hideSoftInputFromWindow( view.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY, _keyboardResultReceiver );
        imm.showSoftInput( view, InputMethodManager.SHOW_IMPLICIT, _keyboardResultReceiver );
    }
    else // if (_keyboardVisible)
    {
        _keyboardVisible = false;
        _keyboardCallback.onHideKeyboard( _keyboardCallbackParam );
    }
}

private ResultReceiver      _keyboardResultReceiver = new ResultReceiver( _keyboardHandler )
{
    @Override
    protected void onReceiveResult( int resultCode, Bundle resultData )
    {
        switch (resultCode)
        {
            case InputMethodManager.RESULT_SHOWN :
            case InputMethodManager.RESULT_UNCHANGED_SHOWN :
                // if (!_keyboardVisible)
                {
                    _keyboardVisible = true;
                    _keyboardCallback.onShowKeyboard( _keyboardCallbackParam );
                }
                break;
            case InputMethodManager.RESULT_HIDDEN :
            case InputMethodManager.RESULT_UNCHANGED_HIDDEN :
                // if (_keyboardVisible)
                {
                    _keyboardVisible = false;
                    _keyboardCallback.onHideKeyboard( _keyboardCallbackParam );
                }
                break;
        }
    }
};

怎么称呼它,在哪里?
Mahdi Astanei'9

0

这是一种解决方法,可以了解软键盘是否可见。

  1. 使用ActivityManager.getRunningServices(max_count_of_services);检查系统上正在运行的服务。
  2. 从返回的ActivityManager.RunningServiceInfo实例中,检查clientCount值以获取软键盘服务。
  3. 每当显示上述软键盘时,上述clientCount都会增加。例如,如果clientCount最初为1,则显示键盘时为2。
  4. 在关闭键盘时,clientCount会减少。在这种情况下,它将重置为1。

一些流行的键盘在其className中具有某些关键字:

  1. Google AOSP = IME
  2. Swype = IME
  3. 快捷键= KeyboardService
  4. Fleksy =键盘
  5. Adaptxt = IME(KPTAdaptxtIME)
  6. 智能=键盘(SmartKeyboard)

在ActivityManager.RunningServiceInfo中,检查ClassNames中的上述模式。另外,ActivityManager.RunningServiceInfo的clientPackage = android,表示键盘已绑定到系统。

可以将上述信息组合起来,以严格的方式确定软键盘是否可见。


0

如您所知,只有在可能发生键入事件时,才会显示android软件键盘。换句话说,只有在聚焦EditText时,键盘才可见。这意味着您可以使用OnFocusChangeListener来获取键盘可见与否的天气。

//Declare this Globally

public boolean isKeyBoardVisible = false;

//In OnCreate *[For Activity]*, OnCreateView *[For Fragment]*

text_send.setOnFocusChangeListener(new View.OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(hasFocus)
            isKeyBoardVisible = true;
        else
            isKeyBoardVisible = false;
    }
});

现在您可以使用isKeyBoardVisible在类中的任何位置变量,以获取键盘为“打开”还是“不打开”的天气信息。对我来说效果很好。

注意:使用InputMethodManager以编程方式打开键盘时,此过程不起作用,因为它不会调用OnFocusChangeListener。


不是真正的hack,在嵌套片段的情况下无法正常工作。不能说活动,因为我还没有尝试过。
antroid

0

我将答案转换为Kotlin,希望这对Kotlin用户有所帮助。

private fun checkKeyboardVisibility() {
    var isKeyboardShowing = false

    binding.coordinator.viewTreeObserver.addOnGlobalLayoutListener {
        val r = Rect()
        binding.coordinator.getWindowVisibleDisplayFrame(r)
        val screenHeight = binding.coordinator.rootView.height

        // r.bottom is the position above soft keypad or device button.
        // if keypad is shown, the r.bottom is smaller than that before.
        val keypadHeight = screenHeight - r.bottom


        if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is perhaps enough to determine keypad height.
            // keyboard is opened
            if (!isKeyboardShowing) {
                isKeyboardShowing = true

            }
        } else {
            // keyboard is closed
            if (isKeyboardShowing) {
                isKeyboardShowing = false

            }
        }
    }
}

0

它与adjustNothing活动标志和生命周期事件一起使用。同样在Kotlin中:

/**
 * This class uses a PopupWindow to calculate the window height when the floating keyboard is opened and closed
 *
 * @param activity The parent activity
 *  The root activity that uses this KeyboardManager
 */
class KeyboardManager(private val activity: AppCompatActivity) : PopupWindow(activity), LifecycleObserver {

    private var observerList = mutableListOf<((keyboardTop: Int) -> Unit)>()

    /** The last value of keyboardTop */
    private var keyboardTop: Int = 0

    /** The view that is used to calculate the keyboard top  */
    private val popupView: View?

    /** The parent view  */
    private var parentView: View

    var isKeyboardShown = false
        private set

    /**
     * Create transparent view which will be stretched over to the full screen
     */
    private fun createFullScreenView(): View {
        val view = LinearLayout(activity)
        view.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT)
        view.background = ColorDrawable(Color.TRANSPARENT)
        return view
    }

    init {
        this.popupView = createFullScreenView()
        contentView = popupView

        softInputMode = LayoutParams.SOFT_INPUT_ADJUST_RESIZE or LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
        inputMethodMode = INPUT_METHOD_NEEDED

        parentView = activity.findViewById(android.R.id.content)

        width = 0
        height = LayoutParams.MATCH_PARENT

        popupView.viewTreeObserver.addOnGlobalLayoutListener {
            val rect = Rect()
            popupView.getWindowVisibleDisplayFrame(rect)

            val keyboardTop = rect.bottom
            if (this.keyboardTop != keyboardTop) {
                isKeyboardShown = keyboardTop < this.keyboardTop
                this.keyboardTop = keyboardTop
                observerList.forEach { it(keyboardTop) }
            }
        }
        activity.lifecycle.addObserver(this)
    }

    /**
     * This must be called after the onResume of the Activity or inside view.post { } .
     * PopupWindows are not allowed to be registered before the onResume has finished
     * of the Activity
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun start() {
        parentView.post {
            if (!isShowing && parentView.windowToken != null) {
                setBackgroundDrawable(ColorDrawable(0))
                showAtLocation(parentView, Gravity.NO_GRAVITY, 0, 0)
            }
        }
    }

    /**
     * This manager will not be used anymore
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun close() {
        activity.lifecycle.removeObserver(this)
        observerList.clear()
        dismiss()
    }

    /**
     * Set the keyboard top observer. The observer will be notified when the keyboard top has changed.
     * For example when the keyboard is opened or closed
     *
     * @param observer The observer to be added to this provider
     */
    fun registerKeyboardTopObserver(observer: (keyboardTop: Int) -> Unit) {
        observerList.add(observer)
    }
}

保持视图始终在键盘上方的有用方法

fun KeyboardManager.updateBottomMarginIfKeyboardShown(
        view: View,
        activity: AppCompatActivity,
        // marginBottom of view when keyboard is hide
        marginBottomHideKeyboard: Int,
        // marginBottom of view when keybouard is shown
        marginBottomShowKeyboard: Int
) {
    registerKeyboardTopObserver { bottomKeyboard ->
        val bottomView = ViewUtils.getFullViewBounds(view).bottom
        val maxHeight = ScreenUtils.getFullScreenSize(activity.windowManager).y
        // Check that view is within the window size
        if (bottomView < maxHeight) {
            if (bottomKeyboard < bottomView) {
                ViewUtils.updateMargin(view, bottomMargin = bottomView - bottomKeyboard +
                        view.marginBottom + marginBottomShowKeyboard)
            } else ViewUtils.updateMargin(view, bottomMargin = marginBottomHideKeyboard)
        }
    }
}

在哪里getFullViewBounds

fun getLocationOnScreen(view: View): Point {
    val location = IntArray(2)
    view.getLocationOnScreen(location)
    return Point(location[0], location[1])
}

fun getFullViewBounds(view: View): Rect {
     val location = getLocationOnScreen(view)
     return Rect(location.x, location.y, location.x + view.width,
            location.y + view.height)
 }

哪里getFullScreenSize

fun getFullScreenSize(wm: WindowManager? = null) =
            getScreenSize(wm) { getRealSize(it) }

private fun getScreenSize(wm: WindowManager? = null, block: Display.(Point) -> Unit): Point {
    val windowManager = wm ?: App.INSTANCE.getSystemService(Context.WINDOW_SERVICE)
            as WindowManager
    val point = Point()
    windowManager.defaultDisplay.block(point)
    return point
}

哪里updateMargin

fun updateMargin(
        view: View,
        leftMargin: Int? = null,
        topMargin: Int? = null,
        rightMargin: Int? = null,
        bottomMargin: Int? = null
) {
    val layoutParams = view.layoutParams as ViewGroup.MarginLayoutParams
    if (leftMargin != null) layoutParams.leftMargin = leftMargin
    if (topMargin != null) layoutParams.topMargin = topMargin
    if (rightMargin != null) layoutParams.rightMargin = rightMargin
    if (bottomMargin != null) layoutParams.bottomMargin = bottomMargin
    view.layoutParams = layoutParams
}

-1

我这样做是这样的,但是只有当您的目标是关闭/打开键盘时,它才会重新显示。

关闭示例:(检查键盘是否已经关闭;如果没有关闭,则关闭)

imm.showSoftInput(etSearch, InputMethodManager.HIDE_IMPLICIT_ONLY, new ResultReceiver(null) {
                    @Override
                    protected void onReceiveResult(int resultCode, Bundle resultData) {
                        super.onReceiveResult(resultCode, resultData);
                        if (resultCode != InputMethodManager.RESULT_UNCHANGED_HIDDEN)
                            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
                    }
                });

问题与找出键盘是否在显示有关
Gopal Singh Sirvi

-1

一个可能正在使用:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    Log.d(
    getClass().getSimpleName(), 
    String.format("conf: %s", newConfig));

    if (newConfig.hardKeyboardHidden != hardKeyboardHidden) {
        onHardwareKeyboardChange(newConfig.hardKeyboardHidden);

        hardKeyboardHidden = newConfig.hardKeyboardHidden;
    }

    if (newConfig.keyboardHidden != keyboardHidden) {
        onKeyboardChange(newConfig.keyboardHidden);

        keyboardHidden = newConfig.hardKeyboardHidden;
    }

}

public static final int KEYBOARDHIDDEN_UNDEFINED = 0;
public static final int KEYBOARDHIDDEN_NO = 1;
public static final int KEYBOARDHIDDEN_YES = 2;
public static final int KEYBOARDHIDDEN_SOFT = 3;

//todo
private void onKeyboardChange(int keyboardHidden) {

}

//todo
private void onHardwareKeyboardChange(int hardKeyboardHidden) {

}

这仅适用于硬件键盘,不适用于软件键盘
anthonymonori 16-10-13


-1

如果您的应用程序支持AndroidR的api,则可以使用以下方法。

In kotlin :
    var imeInsets = view.rootWindowInsets.getInsets(Type.ime()) 
    if (imeInsets.isVisible) { 
        view.translationX = imeInsets.bottom 
    }

注意:这仅适用于AndroidR,低于android版本需要遵循其他一些答案,否则我会为此进行更新。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.