Android Question Custom font on a widget view

Peter Simpson

Expert
Licensed User
Longtime User
Hey @Paulo Rosa,

The only way I know how to do what you are looking for (which is obviously not the only way to do it) is to use Canvas.DrawText to create a TextBitmap, then use the Bitmap on your widget by using RV.SetImage.

Something like this, this is just the basics on how I would do it.
B4X:
'CODE NOT TESTED

    Dim BitmapTxtToImg As Bitmap
        BitmapTxtToImg.InitializeMutable(Width, Height)

    Dim CustomFont As Typeface = Typeface.LoadFromAssets(<YourFont>)
    Dim CanvasImage As Canvas
        CanvasImage.Initialize2(BitmapTxtToImg)

    CanvasImage.DrawText("Hello World", 10dip, 10dip, CustomFont, 28, Colors.RGB(0, 0, 0), "CENTER")

    RV.SetImage(<ImageviewOnYourWidget>, CanvasImage.Bitmap)
    RV.UpdateWidget

I believe that your ImageView on your widget should now say 'Hello World'.

As I said previously, there are multiple ways to achieve your results, this is how I would do it rightly or wrongly. I'm sure that someone else will give you another method.

Enjoy...
 
Last edited:
Upvote 0

Paulo Rosa

Member
Licensed User
Hey @Paulo Rosa,

The only way I know how to do what you are looking for (which is obviously not the only way to do it) is to use Canvas.DrawText to create a TextBitmap, then use the Bitmap on your widget by using RV.SetImage.

Something like this, this is just the basics on how I would do it.
B4X:
'CODE NOT TESTED

    Dim BitmapTxtToImg As Bitmap
        BitmapTxtToImg.InitializeMutable(Width, Height)

    Dim CustomFont As Typeface = Typeface.LoadFromAssets(<YourFont>)
    Dim CanvasImage As Canvas
        CanvasImage.Initialize2(BitmapTxtToImg)

    CanvasImage.DrawText("Hello World", 10dip, 10dip, CustomFont, 28, Colors.RGB(0, 0, 0), "CENTER")

    RV.SetImage(<ImageviewOnYourWidget>, CanvasImage.Bitmap)
    RV.UpdateWidget

I believe that your ImageView on your widget should now say 'Hello World'.

As I said previously, there are multiple ways to achieve your results, this is how I would do it rightly or wrongly. I'm sure that someone else will give you another method.

Enjoy...

I wonder if that code would significantly affect battery lifetime.

Let me explain...

I'm building a very simple app, it's a clock widget. The widget uses a Broadcast Receiver to capture the intent "android.intent.action.TIME_TICK", which occurs every minute. So, every minute my code runs and displays the correct time. Currently the time is shown on a label with standard typeface (DEFAULT), so the processor overhead is minimum, just a pair of code lines every minute to change the label text.

Regards,
 
Upvote 0
Top