Obtener las dimensiones del teclado de software


¿Hay alguna forma de saber el tamaño del teclado que se muestra en la pantalla?

Estoy usando Cocos2dx para programar, pero quiero saber la altura del teclado que se muestra en pantalla en la parte de Android o en la parte de Cocos, no importa.

Sé que Keyboard tiene un método getHeight() pero no quiero crear nuevos teclados, quiero usar el predeterminado.

Author: Yossi Dahan, 2012-11-23

11 answers

Lo hicimos con esto

myLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

                @Override
                public void onGlobalLayout() {

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

                    int screenHeight = parent.getRootView().getHeight();
                    int heightDifference = screenHeight - (r.bottom - r.top);
                    Log.d("Keyboard Size", "Size: " + heightDifference);

                }
            });

Solo redimensionamos las vistas con el teclado, por lo que podríamos usar esto.

 33
Author: Rudy_TM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-25 15:55:45
Rect r = new Rect();
View rootview = this.getWindow().getDecorView(); // this = activity
rootview.getWindowVisibleDisplayFrame(r);

El resultado de esto es la cantidad de espacio que su aplicación utiliza en la pantalla (funciona incluso cuando la actividad es no redimensionada). Obviamente, el espacio restante de la pantalla será utilizado por el teclado ( si es visible)

Id encontrado aquí: https://github.com/freshplanet/ANE-KeyboardSize/blob/master/android/src/com/freshplanet/ane/KeyboardSize/getKeyboardY.java

 20
Author: FDIM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-01 12:24:03

Si su actividad no está a pantalla completa, utilice el siguiente código:

content.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {

                @Override
                public void onGlobalLayout() {
                    // TODO Auto-generated method stub
                    if (keyBoardHeight <= 100) {
                        Rect r = new Rect();
                        content.getWindowVisibleDisplayFrame(r);

                        int screenHeight = content.getRootView()
                                .getHeight();
                        int heightDifference = screenHeight
                                - (r.bottom - r.top);
                        int resourceId = getResources()
                                .getIdentifier("status_bar_height",
                                        "dimen", "android");
                        if (resourceId > 0) {
                            heightDifference -= getResources()
                                    .getDimensionPixelSize(resourceId);
                        }
                        if (heightDifference > 100) {
                            keyBoardHeight = heightDifference;
                        }

                        Log.d("Keyboard Size", "Size: " + heightDifference);
                    }
                    // boolean visible = heightDiff > screenHeight / 3;
                }
            });
 9
Author: Habbot Phan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-10 03:43:11

Si desea calcular la altura del Teclado Virtual mientras su actividad no cambia de tamaño (adjustPan), puede usar este ejemplo:

Https://github.com/siebeprojects/samples-keyboardheight

Utiliza una ventana oculta para calcular la diferencia de altura entre la ventana y la vista raíz de la actividad.

 4
Author: Siebe Brouwer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-22 07:10:56

No se puede decir. No, en serio: simplemente no se puede decir.

El teclado no necesita tener ninguna forma en particular. No tiene que colocarse en la parte inferior de la pantalla (muchas de las opciones más populares no son), no tiene que mantener su tamaño actual cuando cambia los campos de texto (casi ninguno lo hace dependiendo de las banderas). Ni siquiera tiene que ser rectangular . También puede hacerse cargo de toda la pantalla .

 3
Author: ctate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-10 19:37:28

Sé que este es un post antiguo, pero me di cuenta de que la solución elegida para mí no funcionaba en todos los dispositivos. Parecía haber una discrepancia y por lo que implementé esto y parece ser un catch all:

        final int[] discrepancy = new int[1];
        discrepancy[0] = 0;

        // this gets the height of the keyboard
        content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                View rootview = activity.getWindow().getDecorView(); // this = activity
                rootview.getWindowVisibleDisplayFrame(r);

                int screen_height = rootview.getRootView().getHeight();
                int keyboard_height = screen_height - (r.bottom + r.top) - discrepancy[0];

                if (discrepancy[0] == 0) {
                    discrepancy[0] = keyboard_height;
                    if (keyboard_height == 0) discrepancy[0] = 1;
                }

                int margin_bottom = keyboard_height + Helper.getDp(10, activity);

                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) carousel_container.getLayoutParams();
                params.setMargins(0, 0, 0, margin_bottom);

                //boolean visible = heightDiff > screenHeight / 3;
            }
        });

Cuando el oyente es llamado por primera vez, mide la pantalla sin un teclado y si hay una discrepancia, la próxima vez lo explico. Si no hay discrepancia, establezco la discrepancia en 1 solo para que ya no sea 0.

 3
Author: noshaf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-19 08:57:16

En cocos2d-x tenemos CCEditBox.

Dentro de Extensions->GUI->CCEditBox, puedes encontrar la clase CCEditBox.

La belleza es que oculta el teclado de tocar en otro lugar de la escena. y mueve automáticamente el teclado hacia arriba en caso de que su cuadro de edición se colocara demasiado bajo en la escena.

Si está utilizando cocos2d-x v2.1.3, puede navegar al proyecto de ejemplo yendo a

Samples->cpp->TestCpp->Classes->ExtensionTest->EditBoxTest.

Sólo estoy voy a usarlo en lugar de CCTextField a partir de ahora. lo encontré ayer :)

 2
Author: Azhar Yousuf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-05 06:14:15

Después de varias horas de búsqueda, he encontrado una solución si desea establecer windowSoftInput="adjustPan"

Aquí está el fragmento de código:

    final View root  = findViewById(android.R.id.content);
    root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    Rect r = new Rect();
    {
        root.getWindowVisibleDisplayFrame(r);
    }
    @Override
    public void onGlobalLayout() {
        Rect r2 = new Rect();
        root.getWindowVisibleDisplayFrame(r2);
        int keyboardHeight = r.height() - r2.height();
        if (keyboardHeight > 100) {
            root.scrollTo(0, keyboardHeight);
        }
        else {
            root.scrollTo(0, 0);
        }
    }
});

En este código, después de encontrar la altura del teclado, desplazo la vista hasta no cubierta por el teclado, que es la razón principal para encontrar la altura del teclado.

Según los documentos :

void getWindowVisibleDisplayFrame(Rect outRect) : Recuperar el tamaño general de la pantalla visible en la que se ha colocado la ventana a la que se adjunta esta vista.

 1
Author: Ali Zeynali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-07 09:26:16

El ROOT_VIEW de una pantalla de visualización de Android se puede visualizar como una vista de pantalla única con MARCO DE VISUALIZACIÓN VISIBLE que muestra la vista de su actividad.

Este MARCO DE VISUALIZACIÓN VISIBLE se ajusta cuando el TECLADO DE SOFTWARE se muestra u oculta de la pantalla.

NOTA: Por favor, mira las dos imágenes haciendo clic en los enlaces que figuran a continuación para una mejor comprensión

Así que la VISTA RAÍZ de una pantalla se puede visualizar como : Vista raíz de la pantalla screen

El ajuste del MARCO de VISUALIZACIÓN VISIBLE con la apertura y el cierre del TECLADO de SOFTWARE se puede visualizar como : VISIBLE_DISPLAY_SCREEN adjustment

Este ajuste del MARCO de la PANTALLA VISUAL se puede utilizar muy bien para averiguar la altura del teclado como:

(cuando el teclado está abierto)

SOFT_KEYBOARD_HEIGHT = ROOT_VIEW_HEIGHT - (VISUAL_DISPLAY_FRAME_HEIGHT + EXTRA_SCREEN_HEIGHT)

El código para lograr la arriba está:

int mExtraScreenHeight=-1, mKeyboardHeight=-1;
boolean mKeyboardOpen;



    rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

            int rootViewHeight, visibleDisplayFrameHeight, fakeHeight;

            /* (rootViewHeight - visibleDisplayFrameHeight) is not the real height of the keyboard
                it is the fake height as it also consist of extra screen height
                so FAKE_HEIGHT = KEYBOARD_HEIGHT + EXTRA_SCREEN_HEIGHT

                To get keyboard height extra screen height must be removed from fake height
             */

            Rect rect = new Rect();
            rootView.getWindowVisibleDisplayFrame(rect);

            rootViewHeight = rootView.getRootView().getHeight();
            visibleDisplayFrameHeight = rect.height();

            fakeHeight = rootViewHeight-visibleDisplayFrameHeight;

            if (mExtraScreenHeight == -1){
                mExtraScreenHeight=fakeHeight;
            }
            /* Suppose the soft keyboard is open then the VISIBLE_DISPLAY_FRAME is in reduced size
                due to the space taken up by extra screen and the keyboard but when the soft keyboard closes
                then KEYBOARD_HEIGHT=0 and thus FAKE_HEIGHT = EXTRA_SCREEN_HEIGHT
             */
            else if (fakeHeight <= mExtraScreenHeight){
                mExtraScreenHeight=fakeHeight;
                mKeypadOpen=false;
            }
            else if (fakeHeight > mExtraScreenHeight){
                mKeypadHeight=fakeHeight-mExtraScreenHeight;
                mKeypadOpen=true;
            }
        }
    });

NOTA : La función onGlobalLayout() solo se llamará cuando el diseño global cambie, como cuando se abra el teclado. Por lo tanto, el teclado de software debe estar abierto al menos una vez para obtener la altura del teclado de software.

Funcionó para mí ;)

 0
Author: Pratik Gawali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-04 11:52:01

Lo siento por no poder comentar, dos o tres de las respuestas me ayudaron a resolver mi problema y estaban relacionadas con el uso del AddOnGlobalLayoutListener y luego determinar la altura restante antes y después de que apareciera un teclado.

La solución que utilicé se basó en la respuesta de Rudy_TM.

SIN embargo, una cosa que tuve que encontrar fue que para que ese método funcione, debe tener la siguiente línea en algún lugar

Window.SetSoftInputMode(SoftInput.AdjustResize);

Antes tenía SoftInput.AdjustNothing (or algo así) y no funcionaría. Ahora funciona perfecto. Gracias por las respuestas!

 0
Author: Kalikovision,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-21 20:03:35

Respuesta completa y funcionó perfectamente para mí:

  Rect r = new Rect();
  View rootview = this.getWindow().getDecorView(); // this = activity
  rootview.getWindowVisibleDisplayFrame(r);
  int keyboardHeight = rootview.getHeight() - r.bottom;
 0
Author: Amit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-24 04:59:21