BadgeView主要是继承了TextView,所以实际上就是一个TextView,底层放了一个label,可 以自定义背景图,自定义背景颜色,是否显示,显示进入的动画效果以及显示的位置等等;
这是Git上的一个开源项目.
1.从
2.打开activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/iv"
android:layout_width="80dp"
android:layout_height="100dp"
android:scaleType="fitXY" />
<ImageView
android:id="@+id/iv2"
android:layout_width="80dp"
android:layout_height="100dp"
android:layout_marginTop="30dp"
android:scaleType="fitXY"
android:src="@drawable/app_logo" />
<ImageView
android:layout_marginTop="30dp"
android:id="@+id/iv3"
android:layout_width="80dp"
android:layout_height="100dp"
android:scaleType="fitXY"
android:src="@drawable/app_logo" />
</LinearLayout> 3,打开MainActivity.java
public class MainActivity extends Activity {
private ImageView iv;
private ImageView iv2;
private ImageView iv3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
iv2 = (ImageView) findViewById(R.id.iv2);
iv3 = (ImageView) findViewById(R.id.iv3);
Bitmap b1 = getResIcon(getResources(), R.drawable.app_logo);
Bitmap b2 = generatorContactCountIcon(b1,5);
iv.setBackgroundDrawable(new BitmapDrawable(b2));
BadgeView badgeView = new BadgeView(MainActivity.this, iv2);
badgeView.setText("新消息");
badgeView.setTextSize(8.5f);
badgeView.setTextColor(Color.DKGRAY);
badgeView.show();
BadgeView badgeView2 = new BadgeView(MainActivity.this, iv3);
badgeView2.setBackgroundResource(R.drawable.noread);
badgeView2.show();
}
/**
* 获取Icon对应的bitmap
* @param res
* @param resId
* @return
*/
private Bitmap getResIcon(Resources res, int resId) {
Drawable icon = res.getDrawable(resId);
if (icon instanceof BitmapDrawable) {
BitmapDrawable bd = (BitmapDrawable) icon;
return bd.getBitmap();
} else {
return null;
}
}
/**
* 在给定的图片的右上角加上红色提醒数量
*
* @param icon
* 给定的图片
* @return 带联系人数量的图片
*/
private Bitmap generatorContactCountIcon(Bitmap icon,int count) {
// 初始化画布
int iconSize = (int) getResources().getDimension(
android.R.dimen.app_icon_size);
Bitmap contactIcon = Bitmap.createBitmap(iconSize, iconSize,
Config.ARGB_8888);
Canvas canvas = new Canvas(contactIcon);
// 拷贝图片
Paint iconPaint = new Paint();
iconPaint.setDither(true);// 防抖动
iconPaint.setFilterBitmap(true);// 用来对Bitmap进行滤波处理,这样,当你选择Drawable时,会有抗锯齿的效果
Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
Rect dst = new Rect(0, 0, iconSize, iconSize);
canvas.drawBitmap(icon, src, dst, iconPaint);
// 启用抗锯齿和使用设备的文本字距
Paint countPaint = new Paint(Paint.ANTI_ALIAS_FLAG
| Paint.DEV_KERN_TEXT_FLAG);
countPaint.setColor(Color.RED);
countPaint.setTextSize(20f);
countPaint.setTypeface(Typeface.DEFAULT_BOLD);
canvas.drawText(String.valueOf(count), iconSize - 18, 25, countPaint);
return contactIcon;
}
}