public class TipNumberView extends TextView { private Paint mBgPaint; //抗锯齿 PaintFlagsDrawFilter pfd; public TipNumberView(Context context, AttributeSet attrs) { super(context, attrs); //初始化画笔 mBgPaint = new Paint(); mBgPaint.setColor(Color.RED); mBgPaint.setAntiAlias(true); pfd = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); } public TipNumberView(Context context) { this(context, null); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int measuredWidth = getMeasuredWidth();//获取view的宽度 int measuredHeight = getMeasuredHeight();//获取view的高度 //取高度和宽度中的最大值,然后在onDraw();方法中根据较大的那个值作为直径画圆。 int max = Math.max(measuredWidth, measuredHeight); setMeasuredDimension(max, max); } @Override public void setBackgroundColor(int color) { mBgPaint.setColor(color); } //设置通知个数显示 public void setNotifiText(int text) { setText(text + "");//继承了TextView,所以有setText()方法 } public void setNotifiText(String text) { setText(text); } //draw方法比onDraw方法绘制 的东西更多一些。在这里用draw方法来绘制背景。 @Override public void draw(Canvas canvas) { //设置绘图无锯齿 canvas.setDrawFilter(pfd); //下面三个参数:1.参数一是中心点的x轴,参数二是中心点的y轴,参数三是半径,参数四是paint对象; //画圆 canvas.drawCircle(getWidth() / 2, getHeight() / 2, Math.max(getWidth(), getHeight()) / 2, mBgPaint); super.draw(canvas); } } content_main.xml<RelativeLayout 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" tools:context="com.example.tipnumberview.MainActivity" > <RelativeLayout android:layout_width="100dp" android:layout_height="100dp" > <ImageView android:layout_width="fill_parent" android:layout_height="fill_parent" android:src="@mipmap/ic_launcher" /> <com.mrl.fangqqmessagenumber.TipNumberView android:id="@+id/tip" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_width="20dp" android:layout_height="wrap_content" android:textColor="#fff" android:textSize="11sp" android:gravity="center" android:text="13" /> </RelativeLayout> </RelativeLayout> MainActivity.classpublic class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_main); TipNumberView tv = (TipNumberView) findViewById(R.id.tip); //设置消息数目19条 tv.setNotifiText(19); } }
仿微信消息数目提示的自定义view
最新推荐文章于 2023-04-10 15:33:48 发布