如何在运行时更改软键盘的高度?

2024-03-31

我正在设计一个软键盘,当用户在横向和纵向模式之间进行选择时,我想在运行时更改其高度。我知道如何更改 xml 中键的高度,但我需要动态执行此操作。

我唯一想到的就是从Keyboard并覆盖它的设置按键高度 (int height),但它似乎毫无用处,因为整个键盘停止响应我的点击,并且高度(尽管与以前不同)并不关心'height' 在上述函数中。

有什么想法/解决方法吗?


原始解决方案发布于https://stackoverflow.com/a/9695482/1241783 https://stackoverflow.com/a/9695482/1241783但它没有附带解释,所以在这里我稍微扩展一下。

1) 创建一个新类来扩展 Keyboard 类并重写 getHeight() 方法。

@Override
public int getHeight() {
   return getKeyHeight() * 3;
}

注意:这里的数字3是你的总行数,如果你的键盘有5行,就填5。

如果你的键盘行高每行都不同,这里你需要自己计算并返回总高度(单位以像素为单位,我花了一段时间才弄清楚它不是 dp,所以需要将 dp 转换为像素以进行所有计算) 例如:

@Override
public int getHeight() {
   return row1Height + row2Height + row3Height + row4Height + row5Height;
}

2)在同一个类中创建一个新的公共函数。

public void changeKeyHeight(double height_modifier)
{
   int height = 0;
   for(Keyboard.Key key : getKeys()) {
      key.height *= height_modifier;
      key.y *= height_modifier;
      height = key.height;
   }
   setKeyHeight(height);
   getNearestKeys(0, 0); //somehow adding this fixed a weird bug where bottom row keys could not be pressed if keyboard height is too tall.. from the Keyboard source code seems like calling this will recalculate some values used in keypress detection calculation
}

如果您不使用 height_modifier 而是设置为特定高度,则需要自己计算 key.y 位置。

如果您的键盘行高每行都不同,您可能需要检查按键,确定其所属的行并将高度设置为正确的值,否则按键将相互重叠。还将行高存储在私有变量中,以便在上面的 getHeight() 中使用。 PS:在某些配置上,更改键盘高度后我无法按底行键,我发现调用 getNearestKeys() 可以修复该问题,尽管我不太确定原因。

注:key.y 为按键的 y 位置,坐标 0 从键盘顶部开始,随着值的增加而向下。例如坐标为距键盘顶部 100 点到 100 像素:)

3) 最后一步是在扩展InputMethodService 的主类中调用changeKeyHeight。在 onStartInputView() 内部执行(覆盖它),因为这是在更改高度(通过首选项或其他方式)后应该重新绘制键盘的位置。

如果您正在查看 Android 软键盘示例项目,它将是这样的:

@Override public void onStartInputView(EditorInfo attribute, boolean restarting) {
   super.onStartInputView(attribute, restarting);

   // Change the key height here dynamically after getting your value from shared preference or something
   mCurKeyboard.changeKeyHeight(1.5);

   // Apply the selected keyboard to the input view.
   mInputView.setKeyboard(mCurKeyboard);
   mInputView.closing();        

   final InputMethodSubtype subtype = mInputMethodManager.getCurrentInputMethodSubtype();
   mInputView.setSubtypeOnSpaceKey(subtype);
}

Cheers!

额外:如果您需要 dp 到像素转换器,请使用以下代码:

private int convertDpToPx(int dp)
{
   return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在运行时更改软键盘的高度? 的相关文章

随机推荐