Android仿QQ微信未讀消息小紅點BadgeHelper

Android 小紅點 未讀消息功能 BadgeHelper

因為最近的項目需求,翻遍github上的未讀消息紅點開源庫, 發現大部分
不能適配不同情況的佈局, 所以我寫瞭一個能兼容全部的 !
網上的寫法是 繼承TextView然後生成一個小紅點drawable,設置到背景中去, 然後把目標view外層加一層FrameLayout,然後把小紅點添加進去
但這樣做的問題來瞭, 小紅點與目標View 會疊起來!, 擋住文字,!!! 看得我瞎瞭~~~ 而且 他們提供的setOffsetX setpadding 之類的沒卵用,你如果想要偏移小紅點讓它不與下面的View重疊,那是不可能的
所以我的寫法是 為瞭更好的性能,直接繼承View然後畫小紅點背景, 然後把目標view外層加一層LinearLayout 讓小紅點View放目標的右邊,這樣就不會重疊
同時 我也支持設置 重疊模式和非重疊模式

這是效果圖

這裡寫圖片描述

由於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小紅點內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: