我想達到類似下圖的內容:未讀通知/信息的應用程序(在選項卡)內的Android對抗
問題:怎樣才能實現紅色,未讀計數器?我打算設計一些PSD,然後在應用程序中重複使用它?但後來我必須爲每個數字重複很多.png(假設我的限制是99)。但那會是冗餘。
什麼是最佳實踐達到這種效果?
我想達到類似下圖的內容:未讀通知/信息的應用程序(在選項卡)內的Android對抗
問題:怎樣才能實現紅色,未讀計數器?我打算設計一些PSD,然後在應用程序中重複使用它?但後來我必須爲每個數字重複很多.png(假設我的限制是99)。但那會是冗餘。
什麼是最佳實踐達到這種效果?
使用公共TabLayout.Tab setCustomView(INT layoutResId)
創建TextView的佈局和按鈕自定義視圖中使用。你可以使用textView來顯示計數器。
僅供參考
setCustomView
下面是完整的例子:
Example
您還可以使用this庫。
您可以創建自定義視圖並重寫onDraw()方法來繪製數字。你可能想要做的就是像上面一樣準備好一個圖標,除了紅色圓圈中缺少的數字。然後,在自定義視圖中,首先繪製該圖標,然後繪製數字(您將不得不稍微工作一下,以確定繪製它的像素的精確位置,以及如何繪製它,即文本大小,字體顏色)。
模,從資源導入位圖(見例如here)的方法getSomeBitmapFromResources()
,自定義視圖可能會是這個樣子:
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"
/>
當然用實際的位圖尺寸替換寬度和高度。
您是否找到解決方案? –
是的......如果你還沒有回覆 – Juni
你是怎麼做到的? –