仿微博@与#话题#功能的可折叠的TextView_java 话题功能-程序员宅基地

技术标签: android  动画折叠效果  ExpandTextView  weiget  折叠TextView  仿微博@与#话题#功能  

找了很多篇博客, 都没看到我自己想要的那种效果, 就自己写了一个

效果图

使用

第一步:添加如下代码至project的build.gradle里

allprojects {
		repositories {
			...
			maven { url 'https://jitpack.io' }
		}
	}

第二步:在module的build.gradle添加

dependencies {
	        implementation 'com.github.ziyexiao:ExpandTextView:1.0.1'
	}

第三步:在xml布局中配置

  <com.xx.expandtextview.ExpandTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/etv_main" />

第四部: 设置属性

ExpandTextView etvMain = findViewById(R.id.etv_main);

        etvMain.setText(desc)
                .setExpandEnable(true)  //是否可折叠, 默认为true
                .setTextColor(Color.GRAY)       //内容文本颜色
                .setTextSize(14)        //文本字体大小
                .setAnimationDuration(500)  //动画执行时长
                .setBtnExpandText("点击收起")   //折叠文字
                .setBtnSpreadText("点击展开")       //展开文字
                .setBtnGravity(Gravity.END)     //按钮位置
                .setBtnTextColor(Color.BLACK)     //按钮文本颜色
                .setBtnTextSize(18)            //按钮文本大小
                .setShowIcon(true)  //显示箭头
                .setSpanClickable(true, new ExpandTextView.TextSpanClickListener() {  //设置有标签或@某人的点击, 默认为false
                    @Override
                    public void onTextSpanClick(String data) {
                        try {
                            JSONObject jsonObject = new JSONObject(data);
                            int type = jsonObject.getInt("type");
                            String desc = jsonObject.getString("desc");


                            Intent intent = new Intent();
                            switch (type) {
                                case 0:      //个人主页
                                    intent.setClass(MainActivity.this, UserCenterActivity.class);
                                    break;
                                case 1:      //话题主页
                                    intent.setClass(MainActivity.this, TopicCenterActivity.class);
                                    break;
                            }
                            intent.putExtra("desc", desc);
                            startActivity(intent);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

自定义属性

全部代码

package com.expand.demo.expandtextview;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ExpandTextView extends LinearLayout {

    //折叠状态, true为折叠, false为展开
    private boolean expand = true;

    //文本内容
    private String text;

    //是否可折叠
    private boolean expandEnable;

    //文本颜色
    private int textColor;
    //字体大小
    private float textSize;

    //按钮折叠文本内容
    private String btnExpandText;

    //按钮展开内容
    private String btnSpreadText;

    //按钮字体颜色
    private int btnTextColor;
    //折叠后显示的行数
    private int showLines;
    //按钮字体大小
    private float btnTextSize;

    //是否显示箭头图标
    private boolean showIcon;
    //图标icon
    private int iconRes;
    //内容文本
    private TextView mTextView;
    //展开折叠控制按钮
    private TextView mBtnText;
    //展开高度
    private int mTextSpreadHeight;
    //折叠高度
    private int mTextExpandHeight;

    //动画时长
    private long mAnimationDuration;

    //按钮位置
    private int btnGravity = Gravity.CENTER;


    //true, 表示拦截标签span点击事件
    //false, 表示普通文本
    private boolean spanClickable;

    private ImageView mIvArrow;

    private LinearLayout mLlBtn;

    //spanString点击的回调
    public interface TextSpanClickListener {
        void onTextSpanClick(String data);
    }

    private TextSpanClickListener mTextSpanClick;

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

    public ExpandTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ExpandTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandTextView);
        textColor = typedArray.getColor(R.styleable.ExpandTextView_contentTextColor, context.getResources().getColor(R.color.six_three));
        textSize = typedArray.getDimension(R.styleable.ExpandTextView_contentTextSize, 15);

        btnExpandText = typedArray.getString(R.styleable.ExpandTextView_btnExpandText);
        btnSpreadText = typedArray.getString(R.styleable.ExpandTextView_btnSpreadText);
        btnTextSize = typedArray.getDimension(R.styleable.ExpandTextView_btnTextSize, 18);
        btnTextColor = typedArray.getColor(R.styleable.ExpandTextView_btnTextColor, context.getResources().getColor(R.color.six_three));

        showLines = typedArray.getColor(R.styleable.ExpandTextView_showLines, 3);

        showIcon = typedArray.getBoolean(R.styleable.ExpandTextView_showIcon, true);

        iconRes = typedArray.getInt(R.styleable.ExpandTextView_iconRes, R.drawable.ic_arrow_down_gray);

        mAnimationDuration = typedArray.getInt(R.styleable.ExpandTextView_animationDuration, 250);

        spanClickable = typedArray.getBoolean(R.styleable.ExpandTextView_spanClickable, false);

        expandEnable = typedArray.getBoolean(R.styleable.ExpandTextView_expandEnable, true);

        if (TextUtils.isEmpty(btnExpandText)) {
            btnExpandText = "收起";
        }

        if (TextUtils.isEmpty(btnSpreadText)) {
            btnSpreadText = "展开";
        }

        typedArray.recycle();
        init(context);
    }

    private void init(final Context context) {
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        setLayoutParams(params);
        setOrientation(VERTICAL);

        //内容显示文本
        mTextView = new TextView(context);
//        mTextView.setText(text);
        mTextView.setTextSize(textSize);
        mTextView.setTextColor(textColor);
        mTextView.setEllipsize(TextUtils.TruncateAt.END);
        mTextView.setLayoutParams(params);

        //根据SpanClickable状态来设置文本
        setTextBySpanClickableStatus();

        mTextView.setMovementMethod(LinkMovementMethod.getInstance());

        addView(mTextView);

        LayoutParams paramsLlBtn = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mLlBtn = new LinearLayout(context);
        mLlBtn.setOrientation(HORIZONTAL);
        mLlBtn.setGravity(Gravity.CENTER);
        paramsLlBtn.gravity = btnGravity;
        mLlBtn.setLayoutParams(paramsLlBtn);
        mLlBtn.setPadding(15, 15, 15, 15);

        //按钮图标
        LayoutParams paramsImg = new LayoutParams(dip2px(context, 20), dip2px(context, 20));
        mIvArrow = new ImageView(context);
        mIvArrow.setLayoutParams(paramsImg);
        mIvArrow.setImageResource(iconRes);

        if (showIcon) {
            mLlBtn.addView(mIvArrow);
        }

        //控制按钮文本
        mBtnText = new TextView(context);
        mBtnText.setTextColor(btnTextColor);
        mBtnText.setText(btnSpreadText);
        mBtnText.setTextSize(btnTextSize);
        mLlBtn.addView(mBtnText);

        mLlBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                expandByStatus();
            }
        });

        addView(mLlBtn);
    }

    private void expandByStatus() {

        if (expand) {       //折叠状态, 展开

            expandByAnimation(mTextExpandHeight, mTextSpreadHeight);

            mBtnText.setText(btnExpandText);

        } else {        //展开状态, 折叠
            expandByAnimation(mTextSpreadHeight, mTextExpandHeight);

            mBtnText.setText(btnSpreadText);
        }

        expand = !expand;
    }

    /**
     * 折叠与展开动画
     *
     * @param start 开始值
     * @param end   结束值
     */
    private void expandByAnimation(final int start, final int end) {
        mLlBtn.setClickable(false);

        final LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        ValueAnimator valueAnimator = ValueAnimator.ofInt(start, end);

        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                layoutParams.height = (int) animation.getAnimatedValue();
                mTextView.setLayoutParams(layoutParams);

                //图标旋转
                if (start < end) {  //展开, 从0度到180度
                    mIvArrow.setRotation(180 * (1 - (1f * Math.abs(end - (int) animation.getAnimatedValue()) / Math.abs(end - start))));
                } else {    //折叠, 从180度到0度
                    mIvArrow.setRotation(180 * (1f * Math.abs(end - (int) animation.getAnimatedValue()) / Math.abs(end - start)));
                }
            }
        });

        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                if (start < end) {  //展开, 在展开动画开始之前设置行数, 防止文本部分空白展示
                    mTextView.setMaxLines(Integer.MAX_VALUE);
                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (start > end) {  //折叠
                    mTextView.setMaxLines(showLines);
                }

                mLlBtn.setClickable(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        valueAnimator.setDuration(mAnimationDuration);
        valueAnimator.start();
    }

    //只需要测量一次展开高度,测量后置为false
    private boolean canMeasure = true;

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (expand) {
            //测量TextView折叠后的高度
            mTextExpandHeight = mTextView.getMeasuredHeight();
        }

        if (canMeasure) {

            //测量TextView展开高度
            mTextSpreadHeight = mTextView.getMeasuredHeight();

            //文本显示行数大于折叠行数, 显示按钮, 否则隐藏
            mLlBtn.setVisibility(mTextView.getLineCount() > showLines ? VISIBLE : GONE);

            //测量后再设置显示行数
            if (expandEnable) {
                mTextView.setMaxLines(showLines);
            }

            canMeasure = false;
        }
    }

    /**
     * 将dip或dp值转换为px值,保证尺寸大小不变
     */
    private int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public ExpandTextView setText(String text) {
        this.text = text;

        setTextBySpanClickableStatus();

        return this;
    }

    public ExpandTextView setExpandEnable(boolean expandEnable) {
        this.expandEnable = expandEnable;
        if (!expandEnable) {
            removeView(mLlBtn);
        }
        return this;
    }

    public ExpandTextView setTextColor(int textColor) {
        this.textColor = textColor;
        mTextView.setTextColor(textColor);
        return this;
    }

    public ExpandTextView setTextSize(float textSize) {
        this.textSize = textSize;

        mTextView.setTextSize(textSize);
        return this;
    }

    public ExpandTextView setBtnTextColor(int btnTextColor) {
        this.btnTextColor = btnTextColor;
        mBtnText.setTextColor(btnTextColor);
        return this;

    }

    public ExpandTextView setBtnTextSize(int btnTextSize) {
        this.btnTextSize = btnTextSize;
        mBtnText.setTextSize(btnTextSize);
        return this;
    }

    public ExpandTextView setBtnExpandText(String btnExpandText) {
        this.btnExpandText = btnExpandText;
        mBtnText.setText(btnExpandText);
        return this;

    }

    public ExpandTextView setBtnSpreadText(String btnSpreadText) {
        this.btnSpreadText = btnSpreadText;
        mBtnText.setText(btnSpreadText);
        return this;
    }

    public ExpandTextView setAnimationDuration(long animationDuration) {
        mAnimationDuration = animationDuration;
        return this;
    }

    public ExpandTextView setBtnGravity(int btnGravity) {
        this.btnGravity = btnGravity;
        LayoutParams paramsLlBtn = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        paramsLlBtn.gravity = btnGravity;
        mLlBtn.setLayoutParams(paramsLlBtn);
        return this;
    }

    public ExpandTextView setShowIcon(boolean showIcon) {
        this.showIcon = showIcon;
        return this;
    }

    public ExpandTextView setSpanClickable(boolean spanClickable, TextSpanClickListener textSpanClick) {
        this.spanClickable = spanClickable;
        mTextSpanClick = textSpanClick;

        setTextBySpanClickableStatus();
        return this;
    }

    /**
     * 格式化超链接文本内容并设置点击处理
     */
    private CharSequence getClickableHtml(String html) {
        Spanned spannedHtml = Html.fromHtml(html);

        SpannableStringBuilder clickableHtmlBuilder = new SpannableStringBuilder(spannedHtml);
        URLSpan[] urls = clickableHtmlBuilder.getSpans(0, spannedHtml.length(), URLSpan.class);
        for (final URLSpan span : urls) {
            setLinkClickable(clickableHtmlBuilder, span);
        }
        return clickableHtmlBuilder;
    }

    /**
     * 设置点击超链接对应的处理内容
     */
    private void setLinkClickable(final SpannableStringBuilder clickableHtmlBuilder, final URLSpan urlSpan) {
        int start = clickableHtmlBuilder.getSpanStart(urlSpan);
        int end = clickableHtmlBuilder.getSpanEnd(urlSpan);
        int flags = clickableHtmlBuilder.getSpanFlags(urlSpan);

        clickableHtmlBuilder.setSpan(new ClickableSpan() {
            public void onClick(View view) {
                if (mTextSpanClick != null) {
                    //取出a标签的href携带的数据, 并回调到调用处
                    //href的数据类型根据个人业务来定, demo是传的json字符串
                    mTextSpanClick.onTextSpanClick(urlSpan.getURL());
                }
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.linkColor = Color.TRANSPARENT;
                ds.setColor(Color.BLUE);
                ds.setUnderlineText(false);
            }
        }, start, end, flags);
    }


    /**
     * 根据SpanClickable的状态来设置文本
     */
    private void setTextBySpanClickableStatus() {
        if (!TextUtils.isEmpty(text)) {
            if (spanClickable) {
                mTextView.setAutoLinkMask(Linkify.ALL);
                mTextView.setText(getClickableHtml(text));
            } else {
                mTextView.setText(text);
            }
        }
    }
}
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

github地址: GitHub - ziyexiao/ExpandTextView: 仿微博@与#话题#功能的可折叠的TextView

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ziyexiaoxiao/article/details/98749110

智能推荐

Spring、SpringBoot常见面试题与答案_spring和springboot的常见面试题-程序员宅基地

文章浏览阅读390次。SpringSpring Bean 的作用域有哪些?它的注册方式有几种?Spring 容器中管理一个或多个 Bean,这些 Bean 的定义表示为 BeanDefinition 对象,具体包含以下重要信息:Bean 的实际实现类;Bean 的引用或者依赖项;Bean 的作用范围;singleton:单例(默认);prototype:原型,每次调用bean都会创建新实例;request:每次http请求都会创建新的bean;session:同一个http session共享一个bean_spring和springboot的常见面试题

openstack认证服务(认证组件)3_openstack 认证服务-程序员宅基地

文章浏览阅读1.9k次。Openstack认证服务(认证组件)3_openstack 认证服务

职场生存法则:一个外企女白领的日记...-程序员宅基地

文章浏览阅读4.5k次。第11节:人与人的相处(1)   2006-6-7 8∶40∶00  人与人的相处  一、有后台的下属。  我遇见过,也处理得很好。你不能得罪他背后的人,那么就通过他去利用他背后的人。比如说他是老板的亲戚,碰见别的部门有什么搞不定的人,你美言他几句叫他去搞,成功了自然是别人给老板面子,失败了你也可以多多积累他的错误,日后真到不得不踢人的时候也派得上..._外企重视documentation

iOS踩坑App Store Connect Operation Error_sdk version issue. this app was built with the ios-程序员宅基地

文章浏览阅读3.4k次。这个应用程序是用iOS 15.5 SDK构建的。从2023年4月开始,所有提交到应用商店的iOS应用程序都必须使用iOS 16.1 SDK或更高版本构建,包括在Xcode 14.1或更高版本中。目前iOS 开发工具Xcode 版本号是13.4.1 ,系统无法升级,也会导致Xcode无法升级。1、苹果官方提示: 2023年4月开始,开发必须使用 Xcode 14.1 以上的版本,2、目前此电脑无法在升级, 2023年4月开始 ,此电脑就无法正常开发使用,应用程序商店连接操作错误。_sdk version issue. this app was built with the ios 15.5 sdk. all ios and ipa

接单平台汇总_excel接单平台-程序员宅基地

文章浏览阅读335次。接单平台汇总程序员客栈码市开源众包智慧外包实现网猿急送人人开发网开发邦点鸭网快码网英选网外包大师我爱方案网智筹网自由智客接单注意事项:1、没有第三方担保的个人单子,尽量少接2、无需求文档、没有具体要求的不接3、没有预付的不做,尽量用442的分步步骤方式4、没有金刚钻,别揽瓷器活5、急单勿接6、任何不付定金的单子都是耍赖7、不计得失,不怕吃亏..._excel接单平台

CPU如何跑分_cpu跑分教程-程序员宅基地

文章浏览阅读1k次。烤CPU的时候,占用率满了,CPU频率的槽有一些还是空的…… 有没有能跑分的软件?好像有的【聊电Jing】你的CPU性能如何? 来跑个分测试看看吧! | Cinebench R15 & R20 使用教学_哔哩哔哩_bilibili 好像还是免费的Cinebench - Maxon Cinebench - Microsoft Store Apps 频率为什么就是超不过3Ghz? 多核,100度了? 可能频率最高只能这么高,再高可能就烧掉了…… 多核结果.................._cpu跑分教程

随便推点

Linux常用命令(1)_code=exited, status=0/success-程序员宅基地

文章浏览阅读348次。Linux常用命令(1)切换到ROOT用户(su - root)[liu@localhost ~]$ su - root密码:[root@localhost ~]查看IP地址(ifconfig)[root@localhost ~]# ifconfigens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500 inet 192.168.100.47 netmask 255.255.255.0 broad_code=exited, status=0/success

调用百度地图画圈并标出属于圈内的点位信息_bmap.circle-程序员宅基地

文章浏览阅读1.3k次。直接上代码:fanweiss(){//画圈varaaa=this.gaojingDatadebuggervarmap=newBMap.Map("ydmap");//创建Map实例varmPoint=newBMap.Point(this.gaojingData.longitude,this.gaojingData.latitude);//中心点map.setMapStyle({style:"midni..._bmap.circle

VisualVM 插件地址_visualvm 插件中心地址-程序员宅基地

文章浏览阅读1.4k次。VisualVM原插件地址是oracle的打不开,已经移到github上了,具体如下:介绍:https://visualvm.github.io/plugins.html下载地址:https://visualvm.github.io/pluginscenters.html 选择对应JDK版本下载即可! 注意事项:在使用Visual VM进行heapdump分析的时候,发..._visualvm 插件中心地址

understand 代码解析工具的使用_understand代码-程序员宅基地

文章浏览阅读8.8k次,点赞15次,收藏80次。understand 常用操作文章目录understand 常用操作简单介绍软件下载常用基本操作新建工程并添加现有文件如何找到自己当前想要去编辑的文件?如何在当前文件中找到你要编辑的函数?如何跳转到定义?查看当前文件的函数列表如何查看函数都被谁调用了?查看函数的调用逻辑如何查找如何找到函数的被调用图除此之外可以分析出代码的各种结构文本的编辑格式设置双屏一边看代码,一遍看代码地图简单介绍understand对分析代码有非常强的能力,完全可以代替sourceinsight,并且可以在linux上mac上使_understand代码

Oracle 闪回(flashback)数据库到指定时间点_数据库 oracle时间戳闪回-程序员宅基地

文章浏览阅读4.1k次。如果是update,delete类误操作且已经commit,优先考虑使用flashback query进行恢复。select * from test1 as of timestamp to_timestamp('2018-01-13 16:59:29','YYYY-MM-DD hh24:mi:ss');如果是drop或truncate table,则不能使用闪回查询,需要使用备库进行整库..._数据库 oracle时间戳闪回

[bigdata-124] docker+django2.0 构建web服务_docker django print-程序员宅基地

文章浏览阅读660次。在本地运行django1.python3.42.安装django,安装特定版本pip3 install django==2.03.测试安装python3import djangoprint(django.get_version())4.django使用创建一个新目录test_djangopython -m django --version_docker django print

推荐文章

热门文章

相关标签