【发布时间】:2015-10-10 04:43:20
【问题描述】:
我想实现类似于下图的东西:
问题:如何实现红色未读计数器?我要设计一些 psd 然后在应用程序中重用它吗?但是我必须为每个数字复制很多.png(假设我的限制是99)。但那将是多余的。
实现此效果的最佳做法是什么?
【问题讨论】:
-
你找到解决办法了吗?
-
是的...如果您还没有回复
我想实现类似于下图的东西:
问题:如何实现红色未读计数器?我要设计一些 psd 然后在应用程序中重用它吗?但是我必须为每个数字复制很多.png(假设我的限制是99)。但那将是多余的。
实现此效果的最佳做法是什么?
【问题讨论】:
您可以创建一个自定义视图并覆盖 onDraw() 方法来绘制数字。您可能想要做的是像上面一样准备好一个图标,除了红色圆圈中缺少的数字。然后,在自定义视图中,您首先绘制该图标,然后绘制数字(您将不得不做一些工作来计算绘制它的精确位置(以像素为单位),以及如何绘制它,即文本大小,字体、颜色)。
对从资源导入位图的方法 getSomeBitmapFromResources() 取模(参见例如 here),您的自定义视图可能如下所示:
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"
/>
当然用实际的位图尺寸替换宽度和高度。
【讨论】:
使用 public TabLayout.Tab setCustomView(int layoutResId)
使用 TextView 和 Button 创建一个布局,在自定义视图中使用它。你可以使用 textView 来显示计数器。
供参考
setCustomView
以下是完整的示例:
Example
您也可以使用this 库。
【讨论】: