Search code examples
androidandroid-softkeyboardandroid-fonts

Keylabel of Softkeyboard to change text size and font of keytext


I want to customize softkeyboard. I want to change the text size and font of keytext of keylabel. I have tried many methods but no change in keypad.


Solution

  • You can implement a KeyboardView, then you can customize almost everything in the keyboard's design.

    To change de text size you can set the attribute android:keyTextSize.

    Unfortunately the isn't a way to change the font style in the xml, you will need to do it programmatically extending a class from KeyboardView. In this case I would suggest Phillip's answer:

    public class MyKeyboardView extends KeyboardView {
    @Override
    public void onDraw(Canvas canvas) {
        Paint paint = new Paint();
        paint.setTextAlign(Paint.Align.CENTER);
        Typeface font = Typeface.createFromAsset(context.getAssets(),
            "fonts/Hippie.otf"); //Insert your font here.
        paint.setTypeface(font);
    
        List<Key> keys = getKeyboard().getKeys();
        for(Key key: keys) {
            if(key.label != null)
                canvas.drawText(key.label.toString(), key.x, key.y, paint);
            }
        }
    }
    

    Another way would be changing your app's font, like Ankush Bist said:

    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();
        }
      }
    }
    

    Here you can see another similar question: link

    And at last you can fully customize a xml layout like what I did here