Как получить высоту клавиатуры, когда активность создана в android
Я хочу автоматически отображать список с той же высотой клавиатуры устройства, когда пользователь переходит к этому конкретному действию. Для этого я вызываю три метода: showKeyboard(), getKeyboardHeight(), а затем hideKeyboard(), а затем дает высоту этому списку и показывает этот список. Но проблема в том, что я вызываю showKeyboard(), вычисляю высоту, а затем hideKeyboard(), клавиатура не скрывается и остается видимой. Также я получаю рост как 0. Я не могу отобразить этот listView. Есть ли какой-либо другой процесс, чтобы получить высоту клавиатуры или любую коррекцию в нижнем коде? См. Код ниже:
метод showKeyboard() -
private void showKeyboard() {
InputMethodManager keyboard = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(editChatBox, 0);
}
Метод getKeyboardHeight() -
public int getKeyboardHeight() {
final View rootview = this.getWindow().getDecorView();
linearChatLayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
Rect r = new Rect();
rootview.getWindowVisibleDisplayFrame(r);
int screenHeight = rootview.getRootView().getHeight();
int newHeight = screenHeight - (r.bottom - r.top);
if (newHeight > heightOfKeyboard) {
heightOfKeyboard = screenHeight
- (r.bottom - r.top);
// heightOfKeyboard = heightDiff;
}
Log.d("Keyboard Size", "Size: " + heightOfKeyboard);
}
});
return heightOfKeyboard;
}
hideKeyboard() -
private void hidekeyBoard() {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editChatBox.getWindowToken(), 0);
}
Внутри метода onCreate() -
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_new_layout);
ArrayAdapter<String> chatQueAdapter = new ArrayAdapter<>(this,
R.layout.chat_que_row, R.id.textChatQue, queArrays);
myListView.setAdapter(chatQueAdapter);
showKeyboard();
heightOfKeyboard = getKeyboardHeight();
hidekeyBoard();
myListView.getLayoutParams().height = heightOfKeyboard;
myListView.setVisibility(View.VISIBLE);
}
Ответы
Ответ 1
Я добавил глобальный макет в корневом представлении, и мне удалось изменить размер списка в том же размере, что и клавиатура.
Розовая коробка - это измененный размер ListView. Я тестировал это приложение на двух устройствах Samsung, и он отлично работает на обоих.
![введите описание изображения здесь]()
Файл макета
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
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" />
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorAccent"
android:visibility="gone" />
</LinearLayout>
Класс действия
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();
}
}
});
}
}
Опять же, это просто быстрое демо, которое вы можете улучшить в зависимости от ваших потребностей.
Ответ 2
Насколько я знаю, нет идеального решения, которое будет работать все время. Я видел, как многие люди использовали ViewTreeObserver
, чтобы получить высоту клавиатуры, хотя иногда это не срабатывало, это лучше, чем ничего. Попробуйте.
Я написал редактор методов ввода несколько лет назад. Как я помню, нет функции, называемой "getCurrentHeight", открытой из классов IME. Так что не ходите сюда.
И обратите внимание, что в настоящее время многие IME поддерживают изменение высоты клавиатуры во время выполнения (когда она отображается на экране), возможно, вам придется принять это во внимание.
Ответ 3
Пожалуйста, проверьте этот KeyBoard, это приложение предоставило usuage с использованием RelativeLayout onSize изменено https://github.com/w446108264/XhsEmoticonsKeyboard
Ответ 4
Я вычислил высоту с помощью пользовательского прохода, затем вычислил его
private int keyboardHeight;
// passed here 230dp
final float popUpheight = getResources().getDimension(
R.dimen.keyboard_height);
changeKeyboardHeight((int) popUpheight);
// call this where you want height of keyboard
checkKeyboardHeight();
int previousHeightDiffrence = 0;
private void checkKeyboardHeight() {
rootlayout.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
rootlayout.getWindowVisibleDisplayFrame(r);
int screenHeight = rootlayout.getRootView()
.getHeight();
int heightDifference = screenHeight - (r.bottom);
if (Math.abs(previousHeightDiffrence - heightDifference) > 50) {
popupWindow.dismiss();
imageEmoji
.setImageResource(R.drawable.emoji_btn_normal);
}
previousHeightDiffrence = heightDifference;
if (heightDifference > 100) {
isKeyBoardVisible = true;
changeKeyboardHeight(heightDifference);
} else {
isKeyBoardVisible = false;
}
}
});
}
/**
* change height of emoticons keyboard according to height of actual
* keyboard
*
* @param height minimum height by which we can make sure actual keyboard is
* open or not
*/
private void changeKeyboardHeight(int height) {
if (height > 100) {
keyboardHeight = height;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, keyboardHeight);
emoticonsCover.setLayoutParams(params);
}
}
для получения дополнительной информации о выписке из здесь,
Надеюсь, что это поможет вам.
Ответ 5
Используйте OnGlobalLayoutListener для получения высоты клавиатуры или реализации над фрагментом кода
chatRootLayout - это ваш корневой макет xml
передать этот rootLayout в качестве параметра parentLayout в checkKeyboardHeight
private void checkKeyboardHeight(final View parentLayout)
{
chatRootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
Rect r = new Rect();
chatRootLayout.getWindowVisibleDisplayFrame(r);
int screenHeight = chatRootLayout.getRootView().getHeight();
int keyboardHeight = screenHeight - (r.bottom);
if (previousHeightDiffrence - keyboardHeight > 50)
{
// Do some stuff here
}
previousHeightDiffrence = keyboardHeight;
if (keyboardHeight> 100)
{
isKeyBoardVisible = true;
changeKeyboardHeight(keyboardHeight);
}
else
{
isKeyBoardVisible = false;
}
}
});
}
keyboardHeight() Метод: -
private void changeKeyboardHeight(int height)
{
if (height > 100)
{
keyboardHeight = height;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, keyboardHeight);
yourLayout.setLayoutParams(params);
}
}