我正在设计一个软键盘,我想在运行时更改其高度,因为用户可以在横向和纵向模式之间进行选择.我知道如何在xml中更改键的高度,但我需要动态地完成它.
我想到的唯一一件事就是从Keyboard 继承它并覆盖它的setKeysHeight(int height),但它似乎无用,因为整个键盘停止响应我的点击和高度(虽然与以前不同)并不关心' 在上述功能中的高度.
任何想法/解决方法?
Bru*_*uce 16
原始解决方案发布在/sf/answers/678683771/,但它没有解释所以我在这里扩展了一下.
1)创建一个扩展Keyboard类的新类,该类覆盖getHeight()方法.
@Override
public int getHeight() {
return getKeyHeight() * 3;
}
Run Code Online (Sandbox Code Playgroud)
注意:这里的数字3是你的总行数,如果你的键盘有5行,则输5.
如果每行的键盘行高不同,这里你需要自己计算并返回总高度(单位是像素,花了我一段时间才发现它不是dp所以需要将dp转换为像素进行所有计算) 例如:
@Override
public int getHeight() {
return row1Height + row2Height + row3Height + row4Height + row5Height;
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
如果您没有使用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);
}
Run Code Online (Sandbox Code Playgroud)
干杯!
额外:如果你需要一个dp到像素转换器,这里是代码:
private int convertDpToPx(int dp)
{
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7493 次 |
| 最近记录: |