Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the font of a textview within a widget?

Is there a way to change the font in a widget? I've seen some questions/answers on here but some say it can't be done. Others say it can be done but then don't provide much information. I'm talking about a custom font that I put in my assets folder. The font I want to use is Roboto from the design guidelines.

I mostly want to ask because of the other questions stating it isn't possible. I have the Google Currents widget on my Nexus 7 that uses the Roboto font on it's widget so surely it is possible?

The TextView I want to change is well, just a textview. It has no formatting/styles on it at the moment. The only thing I really need is the font changed to Roboto light.

I would appreciate some advice on how to do this. Thanks.

I actually plan on open sourcing the widget I am making here so it could help others too.

like image 362
RED_ Avatar asked Sep 20 '25 06:09

RED_


1 Answers

Is there a way to change the font in a widget?

Yes, but unfortunately you can only use the system fonts. You can use the Roboto fonts natively on Android 4.1+ like this though:

android:fontFamily="sans-serif"           // roboto regular
android:fontFamily="sans-serif-light"     // roboto light
android:fontFamily="sans-serif-condensed" // roboto condensed

The only way to use Roboto on previous versions for your Text would be to create a Bitmap and draw your Text on Canvas like this:

    Bitmap myBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas myCanvas = new Canvas(myBitmap);
    Paint paint = new Paint();
    Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/myFont.ttf");

    paint.setTypeface(font);
    paint.setStyle(Paint.Style.FILL);
    paint.setColor(...);
    paint.setTextSize(...);
    myCanvas.drawText("Hello World", x, y, paint);

And then set it like this to your RemoteView:

rViews.setImageViewBitmap(R.id.myImageView, myBitmap);
like image 133
Ahmad Avatar answered Sep 22 '25 01:09

Ahmad