Как захватить событие «показать / скрыть виртуальную клавиатуру» в Android? - PullRequest
215 голосов
/ 30 ноября 2010

Я хотел бы изменить раскладку в зависимости от того, отображается виртуальная клавиатура или нет. Я искал API и различные блоги, но не могу найти ничего полезного.

Возможно ли это?

Спасибо!

Ответы [ 15 ]

3 голосов
/ 03 декабря 2010

Сандер, я полагаю, вы пытаетесь показать вид, заблокированный программной клавиатурой. Попробуйте это http://android -developers.blogspot.com / 2009/04 / update-Applications-for-on-screen.html .

2 голосов
/ 10 декабря 2013

Вы также можете проверить наличие дочернего нижнего отступа первого DecorView. При отображении клавиатуры будет установлено ненулевое значение.

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    View view = getRootView();
    if (view != null && (view = ((ViewGroup) view).getChildAt(0)) != null) {
        setKeyboardVisible(view.getPaddingBottom() > 0);
    }
    super.onLayout(changed, left, top, right, bottom);
}
2 голосов
/ 24 июня 2013

Я решил проблему с однострочным кодированием текста.

package com.helpingdoc;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

public class MainSearchLayout extends LinearLayout {
    int hieght = 0;
    public MainSearchLayout(Context context, AttributeSet attributeSet) {

        super(context, attributeSet);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.main, this);


    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Log.d("Search Layout", "Handling Keyboard Window shown");
       if(getHeight()>hieght){
           hieght = getHeight();
       }
        final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
        final int actualHeight = getHeight();
        System.out.println("....hieght = "+ hieght);
        System.out.println("....actualhieght = "+ actualHeight);
        System.out.println("....proposedheight = "+ proposedheight);
        if (actualHeight > proposedheight){
            // Keyboard is shown


        } else if(actualHeight<proposedheight){
            // Keyboard is hidden

        }

        if(proposedheight == hieght){
             // Keyboard is hidden
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
0 голосов
/ 11 августа 2015

Скрыть | Показать события для клавиатуры можно прослушать простым взломом в OnGlobalLayoutListener:

 final View activityRootView = findViewById(R.id.top_root);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();

                if (heightDiff > 100) {
                    // keyboard is up
                } else {
                    // keyboard is down
                }
            }
        });

Здесь activityRootView - это корневой вид вашей активности.

0 голосов
/ 22 апреля 2012

Ответ Небойши Томчича мне не помог.У меня есть RelativeLayout с TextView и AutoCompleteTextView внутри.Мне нужно прокрутить TextView вниз, когда клавиатура отображается и когда она скрыта.Для этого я переопределил метод onLayout, и он отлично работает для меня.

public class ExtendedLayout extends RelativeLayout
{
    public ExtendedLayout(Context context, AttributeSet attributeSet)
    {
        super(context, attributeSet);
        LayoutInflater inflater = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.main, this);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        super.onLayout(changed, l, t, r, b);

        if (changed)
        {
            int scrollEnd = (textView.getLineCount() - textView.getHeight() /
                textView.getLineHeight()) * textView.getLineHeight();
            textView.scrollTo(0, scrollEnd);
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...