Android自定义标签页(仿QQ添加标签)

自定义标签页

一、需求分析:

项目有一个添加标签的需求,而且产品要求,根据接口返回的json数据中的颜色设置标签页的背景颜色,乍一看,没有头绪。要是用普通的select难以实现,那就自定义View吧。先给大家看下效果图:图1-1(所有条目可选状态)图1-2(达到最大值,其余条目不可选状态)


1-1.jpg

1-2.jpg

二、代码实现

我的实现思路是自定义View就是写一个View(UserColorTagView)
继承自AppCompatTextView 实现Checkable接口(可选)实现View.OnClickListener(可以被点击)
下面给出全部代码:

public class UserColorTagView extends AppCompatTextView implements Checkable, View.OnClickListener {

    private static final int DEFAULT_TAG_COLOR = Color.BLACK;
    private static final int DEFAULT_TAG_DISABLE_COLOR = Color.parseColor("#979797");

    private int mTagColor;
    private int mDisableColor;
    private Paint mPaint;
    private float mStrokeWidth;

    private RectF mRect;
    private RectF mStrokeRect;

    private boolean mChecked;

    public UserColorTagView(Context context) {
        this(context, null);
    }

    public UserColorTagView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public UserColorTagView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ColorTagView);
        final boolean clickable = a.getBoolean(R.styleable.ColorTagView_tag_clickable, true);
        mTagColor = a.getColor(R.styleable.ColorTagView_tag_color, DEFAULT_TAG_COLOR);
        mDisableColor = a.getColor(R.styleable.ColorTagView_tag_disable_color, DEFAULT_TAG_DISABLE_COLOR);
        mStrokeWidth = a.getDimension(R.styleable.ColorTagView_tag_stroke_width, getResources().getDisplayMetrics().density);
        a.recycle();

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStrokeWidth(mStrokeWidth);

        super.setOnClickListener(this);
        setClickable(clickable);
        changeTextColor();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mRect = new RectF(0, 0, w, h);
        final float stroke = mStrokeWidth / 2;
        mStrokeRect = new RectF(0 + stroke, 0 + stroke, w - stroke, h - stroke);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        final float radius = (mRect.bottom - mRect.top) / 2;
        if (isEnabled()) {
            if (mChecked) {
                mPaint.setStyle(Paint.Style.FILL);
                mPaint.setColor(mTagColor);
                canvas.drawRoundRect(mRect, radius, radius, mPaint);
            } else {
                mPaint.setStyle(Paint.Style.FILL);
                mPaint.setColor(Color.WHITE);
                canvas.drawRoundRect(mRect, radius, radius, mPaint);

                mPaint.setStyle(Paint.Style.STROKE);
                mPaint.setColor(mTagColor);
                canvas.drawRoundRect(mStrokeRect, radius, radius, mPaint);
            }
        } else {
            if (mChecked) {
                mPaint.setStyle(Paint.Style.FILL);
                mPaint.setColor(mTagColor);
                canvas.drawRoundRect(mRect, radius, radius, mPaint);
            }else{
                mPaint.setStyle(Paint.Style.FILL);
                mPaint.setColor(Color.WHITE);
                canvas.drawRoundRect(mRect, radius, radius, mPaint);

                mPaint.setStyle(Paint.Style.STROKE);
                mPaint.setColor(mDisableColor);
                canvas.drawRoundRect(mStrokeRect, radius, radius, mPaint);
            }

        }
        super.onDraw(canvas);
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        changeTextColor();
    }

    @Override
    public void setChecked(boolean checked) {
        mChecked = checked;
        changeTextColor();
        postInvalidate();
    }

    private void changeTextColor() {
        if (isEnabled()) {
            if (isChecked()) {
                setTextColor(Color.WHITE);
            } else {
                setTextColor(mTagColor);
            }
        } else {
            if (isChecked()) {
                setTextColor(Color.WHITE);
            }else{
                setTextColor(mDisableColor);
            }

        }
    }

    @Override
    public boolean isChecked() {
        return mChecked;
    }

    @Override
    public void toggle() {
        setChecked(!mChecked);
        postInvalidate();
    }

    @Override
    public void onClick(View v) {
        toggle();
        if (mListener != null) {
            mListener.onClick(v);
        }
    }

    public void setTagColor(@ColorInt int color) {
        mTagColor = color;
        changeTextColor();
        postInvalidate();
    }

    public void setTagDisableColor(@ColorInt int color) {
        mDisableColor = color;
        changeTextColor();
        postInvalidate();
    }

    private View.OnClickListener mListener;

    @Override
    public void setOnClickListener(@Nullable View.OnClickListener l) {
        mListener = l;
    }
}

下面是UserColorTagView的自定义属性
写在res --> values --> attrs.xml 中

<declare-styleable name="ColorTagView">
        <attr name="tag_clickable" format="boolean" />
        <attr name="tag_color" format="color" />
        <attr name="tag_disable_color" format="color" />
        <attr name="tag_stroke_width" format="dimension" />
</declare-styleable>

里面主要用到的就是这个自定义View
使用方法

/**
     * 获取标签tagview
     *
     * @return
     */
    private UserColorTagView getUserColorTagView() {
        UserColorTagView userColorTagView = new UserColorTagView(mContext);
        userColorTagView.setGravity(Gravity.CENTER);
        userColorTagView.setTextColor(getResources().getColor(R.color.white));
        userColorTagView.setTextSize(14);
        userColorTagView.setEnabled(true);
        userColorTagView.setChecked(false);
        int leftRightPadding = ScreenUtils.dip2px(15, mContext);
        int topBottomPadding = ScreenUtils.dip2px(5, mContext);
        userColorTagView.setPadding(leftRightPadding, topBottomPadding, leftRightPadding, topBottomPadding);
        return userColorTagView;
    }

为了能够给userColorTagView自适应布局换行我在他的外面包了一层
FlowLayout代码布局如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <com.renren.wz.tagselected.widget.FlowLayout
        android:id="@+id/flowLayout_tags"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="30dp"
        android:layout_marginRight="20dp"
        android:minWidth="80dp"
        app:flow_equally="false"
        app:flow_horizontalSpacing="20dp"
        app:flow_maxSelectNum="8"
        app:flow_verticalSpacing="25dp" />

</androidx.core.widget.NestedScrollView>

其实FlowLayout就是可以保证UserColorTagView能够自动换行。
FlowLayout可能有的小伙伴不陌生了。如果不懂的可以百度一下,
或者去github搜索FlowLayout
最后为了大家方便看代码我把整个Demo的github地址给大家。
点我下载Demo

希望对你有所帮助!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,546评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,224评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,911评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,737评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,753评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,598评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,338评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,249评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,696评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,888评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,013评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,731评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,348评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,929评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,048评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,203评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,960评论 2 355

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明先生_X自主阅读 15,981评论 3 119
  • 作为一个入职的新人,我在开会的时候,完全没有什么可以发言的东西。 我的一天是这样度过的,早上在办公室吃个早餐,看着...
    victoriapoint阅读 916评论 0 1
  • 01 前面章节学习了如何获取知识,但如果不进行有效分类管理,我们的大脑就会像杂货间一样杂乱无章,无法快速找到我们想...
    昕昕向荣Amy阅读 343评论 0 0
  • 小诗一首开篇: 《奶爸铭》 人不在多,奶爸就行。 室不在大,有爱则灵。 斯是奶爸,妇女德性。 谈笑有老太,往来无男...
    九爸阅读 464评论 0 50