欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android仿QQ微信未读消息小红点BadgeHelper

程序员文章站 2022-03-20 13:58:45
android 小红点 未读消息功能 badgehelper因为最近的项目需求,翻遍github上的未读消息红点开源库, 发现大部分不能适配不同情况的布局, 所以我写了一个能兼容全部的 !网上的写法是...

android 小红点 未读消息功能 badgehelper

因为最近的项目需求,翻遍github上的未读消息红点开源库, 发现大部分
不能适配不同情况的布局, 所以我写了一个能兼容全部的 !
网上的写法是 继承textview然后生成一个小红点drawable,设置到背景中去, 然后把目标view外层加一层framelayout,然后把小红点添加进去
但这样做的问题来了, 小红点与目标view 会叠起来!, 挡住文字,!!! 看得我瞎了~~~ 而且 他们提供的setoffsetx setpadding 之类的没卵用,你如果想要偏移小红点让它不与下面的view重叠,那是不可能的
所以我的写法是 为了更好的性能,直接继承view然后画小红点背景, 然后把目标view外层加一层linearlayout 让小红点view放目标的右边,这样就不会重叠
同时 我也支持设置 重叠模式和非重叠模式

这是效果图

Android仿QQ微信未读消息小红点BadgeHelper

由于github账号出问题了,没法上传, 所以写到博客上算了

这只是一个小工具类 供大家学习下我的思路, 就不多说了, 具体实现注释里写的很清楚,不太清楚的可以回复问我

#核心类:
##badgehelper .java

 
package com.truescend.gofit.views;

import android.content.context;
import android.content.res.resources;
import android.graphics.canvas;
import android.graphics.paint;
import android.graphics.rect;
import android.graphics.rectf;
import android.support.annotation.intdef;
import android.support.design.widget.tablayout;
import android.util.log;
import android.util.typedvalue;
import android.view.gravity;
import android.view.view;
import android.view.viewgroup;
import android.widget.framelayout;
import android.widget.linearlayout;

import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.reflect.field;

/**
 * 作者:东芝(2018/8/23).
 * 支持 重叠目标模式 和 放目标右上角但不重叠的模式 两种模式 通过setoverlap 设置,  默认为false=不重叠
 */

public class badgehelper extends view {
    private static final string tag = "badgehelper";
    private float density;
    private paint mtextpaint;
    private paint mbackgroundpaint;
    private string text = "0";
    private int number;

    @type
    private int type = type.type_point;
    private boolean isoverlap;
    private final rectf rect = new rectf();
    private int badgecolor = 0xffd3321b; //默认的小红点颜色
    private int textcolor = 0xffffffff;
    private float textsize;
    private int w;
    private int h;
    private boolean issetup;
    private boolean mignoretargetpadding;
    private boolean iscentervertical;
    private int leftmargin;
    private int topmargin;
    private int rightmargin;
    private int bottommargin;

    @intdef({type.type_point, type.type_text})
    @retention(retentionpolicy.source)
    public @interface type {
        int type_point = 0;
        int type_text = 1;
    }


    public badgehelper(context context) {
        super(context);

    }


    private void init(@type int type, boolean isoverlap) {
        this.type = type;
        this.isoverlap = isoverlap;
        density = getresources().getdisplaymetrics().density;

        switch (type) {
            case type.type_point:
                mbackgroundpaint = new paint();
                mbackgroundpaint.setstyle(paint.style.fill);
                mbackgroundpaint.setflags(paint.anti_alias_flag);
                mbackgroundpaint.setcolor(badgecolor);
                //计算小红点无文本情况下的小红点大小,  按屏幕像素计算, 如果你有你自己认为更好的算法, 改这里即可
                w = h = math.round(density * 7f);
                break;
            case type.type_text:
                mbackgroundpaint = new paint();
                mbackgroundpaint.setstyle(paint.style.fill);
                mbackgroundpaint.setflags(paint.anti_alias_flag);
                mbackgroundpaint.setcolor(badgecolor);

                mtextpaint = new paint();
                mtextpaint.setstyle(paint.style.fill);
                mtextpaint.setflags(paint.anti_alias_flag);
                mtextpaint.setcolor(textcolor);//文本颜色
                if (textsize == 0) {
                    mtextpaint.settextsize(density * 10);//文本大小按屏幕像素 计算, 没写死是为了适配各种屏幕,  但如果你有你认为更合理的计算方式 你可以改这里
                } else {
                    mtextpaint.settextsize(textsize);//使用自定义大小
                }

                //计算小红点有文本情况下的小红点大小,  按文本宽高计算, 如果你有你自己认为更好的算法, 改这里即可
                float textwidth = gettextwidth("99", mtextpaint);
                w = h = math.round(textwidth * 1.4f);//让背景比文本大一点
                break;
        }
    }

    /**
     * 设置margin 可用于做偏移
     * @param left
     * @param top
     * @param right
     * @param bottom
     * @return
     */
    public badgehelper setbadgemargins(int left, int top, int right, int bottom) {
        leftmargin = left;
        topmargin = top;
        rightmargin = right;
        bottommargin = bottom;
        return this;
    }
    /**
     * 设置gravity居中

     * @return
     */
    public badgehelper setbadgecentervertical(  ) {
        iscentervertical = true;
        return this;
    }

    /**
     * 设置小红点类型
     *
     * @param type
     * @return
     */
    public badgehelper setbadgetype(@type int type) {
        this.type = type;
        return this;
    }

    /**
     * 设置小红点大小, 默认自动适配
     *
     * @param textsize
     * @return
     */
    public badgehelper setbadgetextsize(int textsize) {
        context c = getcontext();
        resources r;
        if (c == null) {
            r = resources.getsystem();
        } else {
            r = c.getresources();
        }
        this.textsize = typedvalue.applydimension(typedvalue.complex_unit_sp, textsize, r.getdisplaymetrics());
        return this;
    }


    /**
     * 设置小红点文字颜色, 默认白
     *
     * @param textcolor
     * @return
     */
    public badgehelper setbadgetextcolor(int textcolor) {
        this.textcolor = textcolor;
        return this;
    }

    /**
     * 设置重叠模式, 默认是false(不重叠)
     *
     * @param isoverlap 是否把小红点重叠到目标view之上
     * @return
     */
    public badgehelper setbadgeoverlap(boolean isoverlap) {
        return setbadgeoverlap(isoverlap, false);
    }

    /**
     * 设置重叠模式, 默认是false(不重叠)
     *
     * @param isoverlap             是否把小红点重叠到目标view之上
     * @param isignoretargetpadding 是否忽略目标view的padding
     * @return
     */
    public badgehelper setbadgeoverlap(boolean isoverlap, boolean isignoretargetpadding) {
        this.isoverlap = isoverlap;
        this.mignoretargetpadding = isignoretargetpadding;
        if (!isoverlap && isignoretargetpadding) {
            log.w(tag, "警告:只有重叠模式isoverlap=true 设置mignoretargetpadding才有意义");
        }
        return this;
    }

    /**
     * 设置小红点颜色
     *
     * @param mbadgecolor
     * @return
     */
    public badgehelper setbadgecolor(int mbadgecolor) {
        this.badgecolor = mbadgecolor;
        return this;
    }

    /**
     * 设置小红点大小
     *
     * @param w
     * @param h
     * @return
     */
    public badgehelper setbadgesize(int w, int h) {
        this.w = w;
        this.h = h;
        return this;
    }

    /**
     * 是否显示
     * @param enable
     */
    public void setbadgeenable(boolean enable) {
       setvisibility(enable?visible:invisible);
    }


    /**
     * 设置小红点的文字
     *
     * @param number
     */
    public void setbadgenumber(int number) {
        this.number = number;
        this.text = string.valueof(number);
        if (issetup) {
            if(number==0){
                setvisibility(invisible);
            }else{
                setvisibility(visible);
            }
            invalidate();
        }
    }

    public void bindtotargetview(tablayout target, int tabindex) {
        tablayout.tab tab = target.gettabat(tabindex);
        view targetview = null;
        view tabview = null;
        try {
            field viewfield = tablayout.tab.class.getdeclaredfield("mview");
            viewfield.setaccessible(true);
            targetview = tabview = (view) viewfield.get(tab);

        } catch (exception e) {
            e.printstacktrace();
        }

        try {
            if (tabview != null) {
                field mtextviewfield = tabview.getclass().getdeclaredfield("mtextview");//"miconview"
                mtextviewfield.setaccessible(true);
                targetview = (view) mtextviewfield.get(tabview);
            }
        } catch (exception e) {
            e.printstacktrace();
        }
        if (targetview != null) {
            bindtotargetview(targetview);
        }
    }


    /**
     * 绑定小红点到目标view的右上角
     *
     * @param target
     */
    public void bindtotargetview(view target) {
        init(type, isoverlap);
        if (getparent() != null) {
            ((viewgroup) getparent()).removeview(this);
        }
        if (target == null) {
            return;
        }
        if (target.getparent() instanceof viewgroup) {
            viewgroup parent = (viewgroup) target.getparent();

            int groupindex = parent.indexofchild(target);
            parent.removeview(target);

            if (isoverlap) {//[小红点与目标view重叠]模式
                framelayout badgecontainer = new framelayout(getcontext());
                viewgroup.layoutparams targetlayoutparams = target.getlayoutparams();
                badgecontainer.setlayoutparams(targetlayoutparams);

                target.setlayoutparams(new viewgroup.layoutparams(
                        viewgroup.layoutparams.wrap_content, viewgroup.layoutparams.wrap_content));

                parent.addview(badgecontainer, groupindex, targetlayoutparams);
                badgecontainer.addview(target);
                badgecontainer.addview(this);

                framelayout.layoutparams layoutparams = (framelayout.layoutparams) getlayoutparams();
                if(iscentervertical) {
                    layoutparams.gravity =  gravity.center_vertical ;
                }else{
                    layoutparams.gravity = gravity.end | gravity.top;
                }
                if (mignoretargetpadding) {
                    layoutparams.rightmargin = target.getpaddingright() - w;
                    layoutparams.topmargin = target.getpaddingtop() - h / 2;

                }

                setlayoutparams(layoutparams);


            } else {//[小红点放右侧]模式
                linearlayout badgecontainer = new linearlayout(getcontext());
                badgecontainer.setorientation(linearlayout.horizontal);
                viewgroup.layoutparams targetlayoutparams = target.getlayoutparams();
                badgecontainer.setlayoutparams(targetlayoutparams);


                target.setlayoutparams(new viewgroup.layoutparams(
                        viewgroup.layoutparams.wrap_content, viewgroup.layoutparams.wrap_content));

                parent.addview(badgecontainer, groupindex, targetlayoutparams);
                badgecontainer.addview(target);
                badgecontainer.addview(this);
                if(iscentervertical) {
                    badgecontainer.setgravity(gravity.center_vertical);
                }
            }
            boolean hassetmargin = leftmargin>0||topmargin>0||rightmargin>0||bottommargin>0;
            if (hassetmargin&&getlayoutparams() instanceof viewgroup.marginlayoutparams) {
                viewgroup.marginlayoutparams p = (viewgroup.marginlayoutparams) getlayoutparams();
                p.setmargins(leftmargin, topmargin, rightmargin, bottommargin);
                setlayoutparams(p);
            }
            issetup = true;
        } else if (target.getparent() == null) {
            throw new illegalstateexception("目标view不能没有父布局!");
        }

        if(number==0){
            setvisibility(invisible);
        }else{
            setvisibility(visible);
        }

    }

    @override
    protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
        if (w > 0 && h > 0) {
            setmeasureddimension(w, h);
        } else {
            throw new illegalstateexception("如果你自定义了小红点的宽高,就不能设置其宽高小于0 ,否则请不要设置!");
        }
    }


    @override
    protected void ondraw(canvas canvas) {
        super.ondraw(canvas);
        //这里不用解释了 很简单 就是画一个圆形和文字
        rect.left = 0;
        rect.top = 0;
        rect.right = getwidth();
        rect.bottom = getheight();
        canvas.drawroundrect(rect, getwidth() / 2, getwidth() / 2, mbackgroundpaint);

        if (type == type.type_text) {
            float textwidth = gettextwidth(text, mtextpaint);
            float textheight = gettextheight(text, mtextpaint);
            canvas.drawtext(text, getwidth() / 2 - textwidth / 2, getheight() / 2 + textheight / 2, mtextpaint);
        }
    }

    private float gettextwidth(string text, paint p) {
        return p.measuretext(text, 0, text.length());
    }

    private float gettextheight(string text, paint p) {
        rect rect = new rect();
        p.gettextbounds(text, 0, text.length(), rect);
        return rect.height();
    }


}


#使用示例:

public class main2activity extends appcompatactivity {

    private textview mvtypea;
    private textview mvtypeb;
    private textview mvtypec;
    private textview mvtyped;
    private imageview mvtypee;
    private tablayout mtablayout;

    private void initview() {
        mvtypea = (textview) findviewbyid(r.id.vtypea);
        mvtypeb = (textview) findviewbyid(r.id.vtypeb);
        mvtypec = (textview) findviewbyid(r.id.vtypec);
        mvtyped = (textview) findviewbyid(r.id.vtyped);
        mvtypee = (imageview) findviewbyid(r.id.vtypee);
        mtablayout = (tablayout) findviewbyid(r.id.tablayout);
    }
    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main2);
        initview();


        //情况a(有margin时)
        new badgehelper(this)
                .setbadgetype(badgehelper.type.type_point)
                .setbadgeoverlap(false)
                .bindtotargetview(mvtypea);

        //情况b(有padding时)
        new badgehelper(this)
                .setbadgetype(badgehelper.type.type_point)
                .setbadgeoverlap(true, true)//重叠模式+忽略目标viewpadding 效果, 什么意思? 你可以把第二个参数写成false看看会发生什么
                .bindtotargetview(mvtypeb);

        //情况c(默认情况)
        badgehelper badgehelperc = new badgehelper(this)
                .setbadgetype(badgehelper.type.type_text)
                .setbadgeoverlap(false);
        badgehelperc.bindtotargetview(mvtypec);
        badgehelperc.setbadgenumber(6);//数字模式


        //情况d(有权重时)
        new badgehelper(this)
                .setbadgecolor(0xff0f00ff)//顺便演示下 小红点颜色的设置
                .setbadgetype(badgehelper.type.type_point)
                .setbadgeoverlap(false)
                .bindtotargetview(mvtyped);


        //情况e(小红点与图片重叠)+ 数字模式
        badgehelper badgehelpere = new badgehelper(this)
                .setbadgetype(badgehelper.type.type_text)
                .setbadgeoverlap(true, true);//注意 isignoretargetpadding=true时 和 setbadgemargins 不能同时使用
        //.setbadgesize(100,100)//设置小红点的大小, 如果未设置则使用默认宽高, 一般默认就好
        //.setbadgetextsize(15) //设置文本大小,  不设置 则使用默认, 一般默认就好
        badgehelpere.bindtotargetview(mvtypee);
        //任意地方可以刷新数字
        badgehelpere.setbadgenumber(58);//数字


        //情况f(tablayout兼容)
        badgehelper badgehelperf = new badgehelper(this)
                .setbadgetype(badgehelper.type.type_text)
                .setbadgecentervertical()//红点居中
                .setbadgemargins(10,0,0,0)//偏移一下
                .setbadgeoverlap(false);
        badgehelperf.bindtotargetview(mtablayout, 0);
        badgehelperf.setbadgenumber(5);

        new badgehelper(this)
                .setbadgetype(badgehelper.type.type_point)
                .setbadgecentervertical()//红点居中
                .setbadgemargins(10,0,0,0)//偏移一下
                .setbadgeoverlap(false)
                .bindtotargetview(mtablayout,1);

    }

}

#布局:

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context="com.mx.test12.main2activity">


    <textview
        android:background="#220000ff"
        android:id="@+id/vtypea"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:text="情况a(有margin时)" />

    <textview
        android:background="#2200ff00"
        android:id="@+id/vtypeb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="30dp"
        android:text="情况b(有padding时)" />

    <textview
        android:id="@+id/vtypec"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="情况c(默认情况)" />

    <linearlayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <textview
            android:background="#2200ffff"
            android:id="@+id/vtyped"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="情况d(有权重时)" />

        <view
            android:layout_width="0dp"
            android:layout_height="0dp" />
    </linearlayout>


    <imageview
        android:id="@+id/vtypee"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentdescription="情况e(与图片重叠)"
        android:padding="20dp"
        android:src="@mipmap/ic_launcher" />

    <android.support.design.widget.tablayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        app:layout_scrollflags="scroll"
        app:tabindicatorcolor="#057523"
        app:tabindicatorheight="2.0dp"
        app:tabmode="fixed"
        app:tabselectedtextcolor="#057523"
        app:tabtextcolor="#ced0d3">

        <android.support.design.widget.tabitem
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="聊天列表" />

        <android.support.design.widget.tabitem
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="好友列表" />

        <android.support.design.widget.tabitem
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="设置" />

    </android.support.design.widget.tablayout>

</linearlayout>

到此这篇关于android仿qq微信未读消息小红点badgehelper的文章就介绍到这了,更多相关android小红点内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!