我想为Android实现自定义keyboard,并且想在keyboard上应用字体。

我在KeyboardView类中使用Typeface,但这对我不起作用。

 @Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    Paint paint = new Paint();
    paint.setTextAlign(Paint.Align.CENTER);
    int scaledSize = getResources().getDimensionPixelSize(
            R.dimen.alternate_key_label_size);
    Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/Nastaleeq.ttf");
    paint.setTypeface(tf);
    paint.setTextSize(scaledSize);
    paint.setColor(Color.WHITE);
}

最佳答案

一种解决方案是使用keboardView.java而不是android.inputmethodservice.KeyboardView。

您还需要将paint.setTypeface(Typeface.DEFAULT_BOLD)更改为paint.setTypeface(我的字体),并且必须将attrs.xml添加到项目中。

另一个解决方案:

更改应用程序内部的字体样式。
创建一个名为FontOverride的简单类。

import java.lang.reflect.Field;
import android.content.Context;
import android.graphics.Typeface;

public final class FontsOverride {

public static void setDefaultFont(Context context,
        String staticTypefaceFieldName, String fontAssetName) {
    final Typeface regular = Typeface.createFromAsset(context.getAssets(),
            fontAssetName);
    replaceFont(staticTypefaceFieldName, regular);
}

protected static void replaceFont(String staticTypefaceFieldName,
        final Typeface newTypeface) {
    try {
        final Field staticField = Typeface.class
                .getDeclaredField(staticTypefaceFieldName);
        staticField.setAccessible(true);
        staticField.set(null, newTypeface);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    }
}


将此类添加到您的代码中。

public final class Application extends android.app.Application {
@Override
public void onCreate() {
    super.onCreate();
    FontsOverride.setDefaultFont(this, "DEFAULT", "fonts/Nastaleeq.ttf");
    FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/GeezEdit.ttf");

  }
}


在这里您可以看到添加了一些字体/字体名称。这些是外部字体文件,您可以使用它们覆盖键盘视图/标签。

将此应用程序名称添加到android清单文件中的应用程序名称

例:

<application
    android:name=".Application"
    android:allowBackup="false"
    android:installLocation="internalOnly"
    android:label="@string/ime_name"
    android:theme="@style/AppTheme" >


现在将上述替代字体名称更新为您的样式。基本主题或清单应用程序中使用的主题。

例:

 <!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <item name="android:typeface">monospace</item>
</style>


这将有助于更改用户为android项目或应用程序提供的字体。

10-08 03:34