在Android APP的实现中,经常看到 一些信息的提示,比如在微信的未读条数,信息的未读条数。
其中信息的未读条数,一般在Launcher的WorkSpace主界面上,会在SMS/MMS图标上显示一个未读数量的图标。
关于SMS/MMS未读短信的条数,可以通过Resovler查询sms/mms数据库得到,本文模拟一个在contacts图标上叠加一个未读图标的实现。
代码很简单,大致如下:
package com.example.unreadimageview;
import android.support.v7.app.ActionBarActivity;
import android.text.style.BackgroundColorSpan;
import android.util.Log;
import android.R.integer;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebStorage.Origin;
import android.widget.ImageView;
public class MainActivity extends ActionBarActivity {
private ImageView iv = null;
Drawable background = null;
Bitmap orign = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
background = getResources().getDrawable(R.drawable.unread_info_background);
orign = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_contacts);
initialize();
}
private void initialize() {
String finalText = String.valueOf(2);
int textsize = 40;
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setTextSize(textsize);
/**/
int bgWidth = background.getIntrinsicWidth();
int bgHeight = background.getIntrinsicHeight();
Rect textBounds = new Rect();
paint.getTextBounds(finalText, 0, finalText.length(), textBounds);
int textHeight = textBounds.height();
int textWidth = (int) paint.measureText(finalText, 0, finalText.length());
int circleHeight = (int) (bgHeight * 0.71);
/**/
Canvas canvas = new Canvas();
Bitmap bitmap = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
canvas.setBitmap(bitmap);
background.setBounds(0, 0, bgWidth, bgHeight);
background.draw(canvas);
int x = (bgWidth - textWidth) / 2;
int y = (circleHeight + 1 ) - (circleHeight - textHeight) / 2;
canvas.drawText(finalText, x, y, paint);
Bitmap bitmap2 = orign.copy(Bitmap.Config.ARGB_8888,true);
canvas.setBitmap(bitmap2);
canvas.drawBitmap(bitmap, 0, 0, null);
iv.setImageBitmap(bitmap2);
}
}
其中的一些背景图片,请自己到Android源代码中拷贝。
其运行效果如下: