Background
Google Calendar app has an action item that dynamically change according to the current day ("today"):
I'm required to do a very similar thing, but with a slightly different image that surrounds the text.
The problem
I did succeed to make it work, by creating a Drawable that has text and image in it (based on here).
However, I'm don't think I did it well enough :
- Text font might be different across devices, so might not fit well in what I wrote.
- Not sure if it's because of the VectorDrawable or the text, but I think the text doesn't seem so centered . Seems a bit to the left. This is especially true if I use 2 digits:
- For centering vertically, I don't think I did the correct calculation. I tried much more logical things there, but they were not centered.
What I've tried
Here's the full code (also available here in a project) :
TextDrawable.java
public class TextDrawable extends Drawable {
private static final int DEFAULT_COLOR = Color.WHITE;
private static final int DRAWABLE_SIZE = 24;
private static final int DEFAULT_TEXT_SIZE = 8;
private Paint mPaint;
private CharSequence mText;
private final int mIntrinstSize;
private final Drawable mDrawable;
public TextDrawable(Context context, CharSequence text) {
mText = text;
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setColor(DEFAULT_COLOR);
mPaint.setTextAlign(Align.CENTER);
float textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_TEXT_SIZE, context.getResources().getDisplayMetrics());
mPaint.setTextSize(textSize);
mIntrinstSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DRAWABLE_SIZE, context.getResources().getDisplayMetrics());
mDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_backtodate);
mDrawable.setBounds(0, 0, mIntrinstSize, mIntrinstSize);
}
@Override
public void draw(Canvas canvas) {
Rect bounds = getBounds();
mDrawable.draw(canvas);
canvas.drawText(mText, 0, mText.length(),
bounds.centerX(), bounds.centerY() + mPaint.getFontMetricsInt(null) / 3, mPaint); // this seems very wrong
}
@Override
public int getOpacity() {
return mPaint.getAlpha();
}
@Override
public int getIntrinsicWidth() {
return mIntrinstSize;
}
@Override
public int getIntrinsicHeight() {
return mIntrinstSize;
}
@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter filter) {
mPaint.setColorFilter(filter);
}
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val drawable = TextDrawable(this, "1")
imageView.setImageDrawable(drawable)
}
}
ic_backtodate.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="25dp" android:height="25dp"
android:viewportHeight="76.0" android:viewportWidth="76.0">
<path
android:fillColor="#ffffff" android:fillType="evenOdd"
android:pathData="M47.294,60.997H28.704C21.148,60.997 15,54.755 15,47.083V28.905c0,-7.672 6.148,-13.913 13.704,-13.913h18.59C54.852,14.992 61,21.233 61,28.905v18.178c0,7.672 -6.148,13.914 -13.706,13.914zM57.592,28.905c0,-5.763 -4.62,-10.453 -10.298,-10.453h-18.59c-5.676,0 -10.296,4.69 -10.296,10.453v18.178c0,5.765 4.62,10.454 10.296,10.454h18.59c5.678,0 10.298,-4.689 10.298,-10.454z"/>
</vector>
The questions
How can I overcome the different fonts issues? I already use "Lato" font globally (not in the sample app, but in the real app, using "downloaded fonts" API of the support library, but having them built into the app instead), but I don't think
Paint
Object can use it, right?How can I center the text well?
I've looked, via View-hierarchy tool, at how Google Calendar works for this part. To me it seems they just used TextView. How did they do it? Maybe using a 9-patch? But does it work well for Toolbar items?
EDIT:
For now, because I'm tight on schedule, I can't use the drawable solution. Would still be nice to know how to do it well.
My current solution doesn't involve it. I just use a special view that mimics a normal action item. It's not perfect (doesn't fully mimics a real action item), but it will be enough for now. Because it's not perfect, I wrote about it on a new thread, here.
EDIT: since this actually can work well, and still stay as a normal action item, I've decided to give it another try.
I've managed to center the text nicely, but the font is the issue now. It seems that if the OS uses a font of its own, even if I've set "Lato" to be the one of the app, it's not used in the drawable I've made:
I think it's the last issue I need to fix here.
Here's the code:
styles.xml
<item name="android:fontFamily" tools:targetApi="jelly_bean">@font/lato</item>
<item name="fontFamily">@font/lato</item>
MainActivity.kt
class MainActivity : AppCompatActivity() {
lateinit var textDrawable: TextDrawable
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textDrawable = TextDrawable(this, "1")
setSupportActionBar(toolbar)
val handler = Handler()
val runnable = object : Runnable {
var i = 1
override fun run() {
if (isFinishing||isDestroyed)
return
textDrawable.text = (i + 1).toString()
i = (i + 1) % 31
handler.postDelayed(this, 1000)
}
}
runnable.run()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menu.add("goToToday").setIcon(textDrawable).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
menu.add("asd").setIcon(R.drawable.abc_ic_menu_copy_mtrl_am_alpha).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
return super.onCreateOptionsMenu(menu)
}
}
TextDrawable.kt
class TextDrawable(context: Context, text: CharSequence) : Drawable() {
companion object {
private val DEFAULT_COLOR = Color.WHITE
private val DEFAULT_TEXT_SIZE = 12
}
var text: CharSequence = text
set (value) {
field = value
invalidateSelf()
}
private val mPaint: TextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
private val mDrawable: Drawable?
init {
mPaint.color = DEFAULT_COLOR
mPaint.textAlign = Align.CENTER
val textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_TEXT_SIZE.toFloat(), context.resources.displayMetrics)
mPaint.textSize = textSize
mDrawable = AppCompatResources.getDrawable(context, R.drawable.ic_backtodate)
mDrawable!!.setBounds(0, 0, mDrawable.intrinsicWidth, mDrawable.intrinsicHeight)
}
override fun draw(canvas: Canvas) {
val bounds = bounds
mDrawable!!.draw(canvas)
canvas.drawText(text, 0, text.length,
bounds.centerX().toFloat(), (bounds.centerY() + mPaint.getFontMetricsInt(null) / 3).toFloat(), mPaint) // this seems very wrong, but seems to work fine
}
override fun getOpacity(): Int = mPaint.alpha
override fun getIntrinsicWidth(): Int = mDrawable!!.intrinsicWidth
override fun getIntrinsicHeight(): Int = mDrawable!!.intrinsicHeight
override fun setAlpha(alpha: Int) {
mPaint.alpha = alpha
invalidateSelf()
}
override fun setColorFilter(filter: ColorFilter?) {
mPaint.colorFilter = filter
invalidateSelf()
}
}
EDIT:
I think I've found how to have a font for the text, by using :
mPaint.typeface=TypefaceCompat.createFromResourcesFamilyXml(...)
Not sure though how to fill the parameters. Still investigating...
Drawable
class where text (number) drawing is done using low levelCanvas
stuff and this should be done that way - basically OP does not know how to do that right – ChrisDrawable
is perfectly OK - this is how dynamic content should be presented onTextView
/ImageView
etc – Chris