[英]Change font of custome key (label) of android custom keyboard
我在更改 android 自定義鍵盤的自定義鍵的字體樣式(非英語 - Unicode)時遇到問題。 我遵循了類似於此鏈接的答案的內容,對於單字符按鈕似乎工作正常。 它將整個應用程序的字體更改為新字體,包括鍵盤的單個字符鍵。 如果我想更改關鍵文本的大小,我可以使用以下兩個條目
android:keyTextSize="25sp" // for single character keys
android:labelTextSize="20sp" // for multiple character keys
但不幸的是,上面鏈接中的方法僅適用於單字符鍵。 有沒有辦法設置多個字符鍵的字體。
例如,請參見下圖:第一個按鈕具有一些默認系統字體,而第二個和第三個按鈕具有正確的字體。
編輯:閱讀Bhavita Lalwani 的回答后,我開始思考。
if (label != null) {
// For characters, use large font. For labels like "Done", use small font.
if (label.length() > 1 && key.codes.length < 2) {
paint.setTextSize(mLabelTextSize);
paint.setTypeface(Typeface.DEFAULT_BOLD);
} else {
paint.setTextSize(mKeyTextSize);
paint.setTypeface(Typeface.DEFAULT);
}
}
這里說
if (label.length() > 1 && key.codes.length < 2)
因此,僅當它們具有單個代碼時,它才會對多個字符使用 BOLD 字體。 例如。 我認為 Android Engs 正在考慮這些事情。 ???
Keyboard.KEYCODE_DONE
Keyboard.KEYCODE_DELETE
因此,丑陋的解決方法是添加多個代碼並僅在需要時使用第一個代碼。
<Key android:codes="5001,1" android:keyLabel="AB" android:keyWidth="12%p" />
現在每個帶有多個代碼的鍵也使用 DEFAULT 字體。 這現在有效,(直到我找到合適的解決方案:))
我在創建印地語自定義鍵盤時遇到了類似的問題。(非英語-Unicode)
因此,讓我們找出發生這種變化的罪魁禍首。
第 701-709 行
if (label != null) {
// For characters, use large font. For labels like "Done", use small font.
if (label.length() > 1 && key.codes.length < 2) {
paint.setTextSize(mLabelTextSize);
paint.setTypeface(Typeface.DEFAULT_BOLD);
} else {
paint.setTextSize(mKeyTextSize);
paint.setTypeface(Typeface.DEFAULT);
}
}
這意味着它將多字符標簽制作為粗體和不同大小。 並且單個字符標簽保持原樣。
解決方案
創建一個擴展此 KeyboardView 類的 CustomKeyboardView 類
public class CustomKeyboardView extends KeyboardView {
public CustomKeyboardView(Context context, AttributeSet attrs) {
super(context, attrs);
}
現在在這個 CustomKeyboardView 類中,覆蓋 onDraw 方法。 在畫布上繪制鍵盤和按鍵時將調用此方法
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint mpaint = new Paint();
mpaint.setTypeface(Typeface.DEFAULT_BOLD); //to make all Bold. Choose Default to make all normal font
mpaint.setTextSize(24); // in px
List<Key> keys = getKeyboard().getKeys();
for (Keyboard.Key key : keys) {
if (key.label != null) {
String keyLabel = key.label.toString();
canvas.drawText(keyLabel, key.x + key.width, key.y + key.height, mpaint);
} else if (key.icon != null) {
key.icon.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
key.icon.draw(canvas);
}
}
}
您可以使用此作弊碼將 sp 用於 setTextSize 方法
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="custom_text_size">25sp</dimen>
</resources>
和
mpaint.setTextSize(getResources().getDimensionPixelSize(R.dimen.custom_text_size));
最后就像我們以前創建的鍵盤一樣,
KeyboardView kv = (CustomKeyboardView) getLayoutInflater().inflate(R.layout.mainkeyboard, null); //mainkeyboard
Keyboard keyboard = new Keyboard(this, R.xml.hindi); //Your Keyboard Layout
kv.setKeyboard(keyboard); //Set the keyboard
你很高興去。
希望它有幫助:D
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.