原始解决方案发布在https://stackoverflow.com/a/9695482/1241783,但它没有附带解释,所以我在这里扩展一下。
1) 创建一个新类来扩展覆盖 getHeight() 方法的 Keyboard 类。
@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);
}
干杯!
额外:如果您需要 dp 到像素转换器,代码如下:
private int convertDpToPx(int dp)
{
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}