[英]Unread Notifications/Messages counter within the app (in tabs) android
我想实现类似于下图的效果:
问题:我们如何获得红色的未读计数器? 我要设计一些psd,然后在应用程序中重复使用吗? 但是然后我必须为每个数字重复很多.png(假设我的上限是99)。 但这将是多余的。
实现此效果的最佳实践是什么?
您可以创建一个自定义View并重写onDraw()方法来绘制数字。 您可能想要做的是像上面一样准备一个完整的图标,除了红色圆圈中缺少的数字。 然后,在自定义视图中,首先绘制该图标,然后绘制数字(您将需要做一些工作以得出像素的精确位置,以及绘制位置,绘制方式(即文本大小,字体颜色)。
对从资源中导入位图的方法getSomeBitmapFromResources()
模化(请参见此处 ),您的自定义View可能类似于以下内容:
public class MyView extends View {
//Fields:
private Paint paint; //Need a Paint object for colors, fonts, etc.
private RectF rect;
private int numberToPaint;
//Constructors:
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
//Choose the text properties that work for you here:
paint.setColor(Color.WHITE);
paint.setTypeface(Typeface.create("sans-serif", Typeface.BOLD));
paint.setTextSize(12);
}
public MyView(Context context) {
this(context, null);
}
//Most importantly: override onDraw for rendering of the view:
@Override
protected void onDraw(Canvas canvas) {
rect.set(0, 0, getWidth(), getHeight()); //But: make sure your View
//will have the same size of the Bitmap you use! Set the size in XML!
canvas.drawBitmap(getSomeBitmapFromResources(), null, rect, paint);
//Here you will have to carefully choose the position of the text.
//Also consider that depending on numberToPaint the x-coordinate may have to
//be modified. Likely you want to use the Paint.getTextBounds method determine the size.
canvas.drawText("" + numberToPaint, 60, 30, paint);
}
public void chooseNumberAndDraw(int n) {
numberToPaint = n;
postInvalidate(); //Force redraw
}
}
在XML中,您想使用类似的标签添加自定义视图
<com.mysite.myproject.MyView
android:layout_width="64dp"
android:layout_height="64dp"
/>
当然用实际的位图尺寸代替宽度和高度。
使用公共TabLayout.Tab setCustomView(int layoutResId)
使用TextView和Button创建一个布局,在Custom视图中使用它。 您可以使用textView显示计数器。
以供参考
setCustomView
以下是完整的示例:
例
您也可以使用此库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.