我的应用程序中有一个自定义键盘,想根据用户偏好在运行时更改文本颜色。我能够在XML中设置KeyTextColor,但没有这样的属性来以编程方式设置它。这是我在 XML 中设置的方式:
<?xml version="1.0" encoding="utf-8"?>
<app:android.inputmethodservice.KeyboardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/keyboard"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent"
android:keyBackground="@drawable/key_background"
android:keyPreviewHeight="@dimen/dp_0"
android:keyTextSize="40sp"
android:keyTextColor="#00C853">//I set green text color here
</app:android.inputmethodservice.KeyboardView>
想要从程序中设置相同的KeyTextColor。有什么想法吗?
这不是你问的,但它解决了我的问题。您可以通过在布局文件夹中添加不同的键盘来定义不同的主题.xml就像您问题中的键盘一样(;并更改它们的运行时。
@Override
public View onCreateInputView() {
...
int theme_id=keyboard_prefs.getKeyboardThemeID();
if(theme_id== KeyboardConstants.KEYBOARD_THEME_DARK_ID)
mInputView=(LatinKeyboardView) getLayoutInflater().inflate(R.layout.keyboard_dark, null);
else //if(theme_id==2)
mInputView=(LatinKeyboardView) getLayoutInflater().inflate(R.layout.keyboard_light, null);
}
首先,创建一个从键盘视图扩展的类(假设它的名称是 mKeyboardView
(。
然后更改您的 XML 标记并使 android:keyTextColor
= 中的颜色透明为:
<com.example.mKeyboardView
...
android:keyTextColor="@android:color/transparent"
>
</com.example.mKeyboardView>
然后在mKeyboardView中覆盖onDraw
函数,并手动绘制字母,如下所示:
public class mKeyboardView extends KeyboardView
@ColorInt private int MY_COLOR = 0XFF263238;
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
List<Keyboard.Key> keys = getKeyboard().getKeys();
for (Keyboard.Key key : keys) {
drawKey(key, canvas);
}
}
Paint setupKeyText() {
Paint paint = new Paint();
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(70);
paint.setFakeBoldText(false);
paint.setColor(MY_COLOR);
return paint;
}
void drawKeyText(Keyboard.Key key, Canvas canvas) {
if (key.label != null && !key.label.toString().isEmpty()) {
Paint paint = setupKeyText();
int x = key.x + (int) (key.width / 2.0);
int y = key.y + (int) ((key.height /2) + (key.height /3.5));
canvas.drawText(key.label.toString(), x , y, paint);
}
}
}
如上面的代码,您可以控制字体大小、颜色、粗细和许多其他属性。
希望我的回答对某人有所帮助。