I want to implement custom keyboard
for android and I want to apply font on keyboard
.
I am using Typeface in KeyboardView
class but this is not work for me.
@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);
}
One solution is to use keboardView.java instead of android.inputmethodservice.KeyboardView.
You also need to change paint.setTypeface(Typeface.DEFAULT_BOLD) to paint.setTypeface(my font) and you must add attrs.xml to your project.
Another solution:
changing the font style inside the application. create a simple class named 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();
}
}
}
add this class to your code.
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");
}
}
here you can see that some fonts/fontname are added. These are the external font files which you can use to override into your keyboard view/labels.
add this Application name into the android manifest file application name
example:
<application
android:name=".Application"
android:allowBackup="false"
android:installLocation="internalOnly"
android:label="@string/ime_name"
android:theme="@style/AppTheme" >
now update the above-override font name into your style. base theme or the theme which you are using at your manifest application.
example:
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:typeface">monospace</item>
</style>
This will work to change the user provided the font to the android project or application.