How to Get Height of Keyboard

How to get height of Keyboard?

Swift

You can get the keyboard height by subscribing to the UIKeyboardWillShowNotification notification. (Assuming you want to know what the height will be before it's shown).

Swift 4

NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
}
}

Swift 3

NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil
)
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
}
}

Swift 2

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
func keyboardWillShow(notification: NSNotification) {
let userInfo: NSDictionary = notification.userInfo!
let keyboardFrame: NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.CGRectValue()
let keyboardHeight = keyboardRectangle.height
}

Is there any way in Android to get the height of virtual keyboard of device

Yes you can, with the help of Viewtree Observer and global layout listener, just try below mentioned steps

  1. Get the root view of your layout
  2. get the Viewtree observer for this root, and add a global layout listener on top of this.

now whenever soft keyboard is displayed android will re-size your screen and you will receive call on your listener. That's it only thing you now need to do is calculate difference between height which your root view has after re-size and original size. If difference is more then 150 consider this as a keyboard has been inflated.

Below is a sample code

root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
public void onGlobalLayout(){
int heightDiff = root.getRootView().getHeight()- root.getHeight();
// IF height diff is more then 150, consider keyboard as visible.
}
});

Regards,
Techfist

How to get a height of a Keyboard in React-Native?

This is what I did:

If the app has "Authorization / Log-in / Sign-up screen" then:

  1. In componentWillMount add KeyboardListeners as explained here:

    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
  2. Add autoFocus to e-mail / phone number / any other "first" TextInput on the page, so that when the screen loads, the Keyboard pops-up.

  3. In _keyboardDidShow function, that is used as a KeyboardListener, do the follows:

    _keyboardDidShow(e) {
    this.props.navigation.setParams({
    keyboardHeight: e.endCoordinates.height,
    normalHeight: Dimensions.get('window').height,
    shortHeight: Dimensions.get('window').height - e.endCoordinates.height,
    });
    }

    Dimensions is an API of React-Native, do not forget to import it just like you import any React-Native component.

  4. After that, while redirecting to the next page, pass these params and do not forget to keep on passing them to other screens in order not to lose this data:

    this.props.navigation.navigate('pageName', { params: this.props.navigation.state.params });

How to get height of keyboard when activity created in android

I added global layout on root view and I was able to resize list view to same size as Keyboard.

The Pink Box is the resized ListView . I have tested this sample app on 2 Samsung devices and it work fine on Both.

Sample Image

Layout File


android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

android:id="@+id/edt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:inputType="text"
android:maxLines="1" />

android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorAccent"
android:visibility="gone" />

Activity class

import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.fet.minebeta.R;

public class ListActivity extends AppCompatActivity {

PagerAdapter adapterViewPager;
ViewPager viewPager;
private int heightDiff;
private ListView myListView;
private EditText editChatBox;

private boolean wasOpened;
private final int DefaultKeyboardDP = 100;
// Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff
private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);

myListView = (ListView) findViewById(R.id.list);
editChatBox = (EditText) findViewById(R.id.edt);

//Listen for keyboard height change
setKeyboardListener();

// InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
// editChatBox.requestFocus();
// inputMethodManager.showSoftInput(editChatBox, 0);
//
// if (getCurrentFocus() != null) {
// inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
// inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
// }
//
// getWindow().setSoftInputMode(
// WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
// );
}


public final void setKeyboardListener() {

final View activityRootView = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);

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

private final Rect r = new Rect();

@Override
public void onGlobalLayout() {
// Convert the dp to pixels.
int estimatedKeyboardHeight = (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics());

// Conclude whether the keyboard is shown or not.
activityRootView.getWindowVisibleDisplayFrame(r);
heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
boolean isShown = heightDiff >= estimatedKeyboardHeight;

if (isShown == wasOpened) {
Log.d("Keyboard state", "Ignoring global layout change...");
return;
}

wasOpened = isShown;

if (isShown) {

//Set listview height
ViewGroup.LayoutParams params = myListView.getLayoutParams();
params.height = heightDiff;
myListView.setLayoutParams(params);
myListView.requestLayout();
myListView.setVisibility(View.VISIBLE);

Toast.makeText(ListActivity.this, "KeyBoard Open with height " + heightDiff +
"\n List View Height " + myListView.getHeight(), Toast.LENGTH_SHORT).show();

}
}
});
}
}

Again this is just quick demo you can enhance things according to your need.

How to get 'Keyboard height before it opens' in React Native?

I don't know a very clean way to do this, but you could show the keyboard, get the height, then replace the keyboard with your view.

How to get actual keyboard height (keyboard height minus safe area insets)

First you have to get Safe Area bottom height and then
exclude it from keyboard total height. In this way you will get only
keyboard height without bottom safe area.

pesudo code:

let keyboardHeight = your keyboard height - bottomPadding

if #available(iOS 11.0, *) {
let window = UIApplication.shared.keyWindow
let bottomPadding = window?.safeAreaInsets.bottom
}

Hope it will help you.



Related Topics



Leave a reply



Submit