开源可翻折的TextViewExpandableTextView

Version:1.0StartHTML:000000221EndHTML:000087781StartFragment:000027003EndFragment:000087708StartSelection:000027003EndSelection:000087702SourceURL:https://blog.csdn.net/qq_22060403/article/details/80649484

实现的效果图如下 ;

点击查看详情把显示不全的数据显示出来 产接下里

接下来  我们来看下布局 

                    >" android:textsize="12sp" android:textcolor="@color/colorPrimary" android:paddingright="10dp" android:layout_margintop="9dp" android:background="@android:color/transparent" android:layout_gravity="right|bottom">   

布局文件相对比较简单   

java代码相对比较简单     下面上代码  

public class MainActivityextends AppCompatActivity {

ExpandableTextViewexpand_text_view;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        expand_text_view = findViewById(R.id.expand_text_view);

        expand_text_view.setText("adasd asd        " +

"  asd asd asd asd asd asdasdasddasdasdasdasdasdddddsadsdasd s dasd as das dasd sad asd    asd asd asd " +

" ads asd asd as das ads asd d asd as dasd asd这里是内容信息正文," +

"这里是内容信息正文,这里是内容信息正文,这里是内容信息正文,这里是内容信息正文,这里是内容信息正文,这里是内容信息正文,这里是内容信息正文,这里是内容信息正文。 ");

    }

}

自定义view

class ExpandableTextViewextends LinearLayoutimplements View.OnClickListener {

private static final StringTAG = ExpandableTextView.class.getSimpleName();

    /* The default number of lines */

    private static final int MAX_COLLAPSED_LINES =8;

    /* The default animation duration */

    private static final int DEFAULT_ANIM_DURATION =300;

    /* The default alpha value when the animation starts */

    private static final float DEFAULT_ANIM_ALPHA_START =0.7f;

    protected TextViewmTv;

    protected TextViewmTextView; // Button to expand/collapse

    private boolean mRelayout;

    private boolean mCollapsed =true; // Show short version as default.

    private int mCollapsedHeight;

    private int mTextHeightWithMaxLines;

    private int mMaxCollapsedLines;

    private int mMarginBetweenTxtAndBottom;

    private int mAnimationDuration;

    private float mAnimAlphaStart;

    private boolean mAnimating;

    /* Listener for callback */

    private OnExpandStateChangeListenermListener;

    /* For saving collapsed status when used in ListView */

    private SparseBooleanArraymCollapsedStatus;

    private int mPosition;

    public ExpandableTextView(Context context) {

this(context, null);

    }

public ExpandableTextView(Context context, AttributeSet attrs) {

super(context, attrs);

        init(attrs);

    }

@TargetApi(Build.VERSION_CODES.HONEYCOMB)

public ExpandableTextView(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

        init(attrs);

    }

@Override

    public void setOrientation(int orientation) {

if (LinearLayout.HORIZONTAL == orientation) {

throw new IllegalArgumentException("ExpandableTextView only supports Vertical Orientation.");

        }

super.setOrientation(orientation);

    }

@Override

    public void onClick(View view) {

if (mTextView.getVisibility() != View.VISIBLE) {

return;

        }

mCollapsed = !mCollapsed;

        if (mCollapsedStatus !=null) {

mCollapsedStatus.put(mPosition, mCollapsed);

        }

// mark that the animation is in progress

        mAnimating =true;

        Animation animation;

        if (mCollapsed) {

animation =new ExpandCollapseAnimation(this, getHeight(), mCollapsedHeight);

        }else {

animation =new ExpandCollapseAnimation(this, getHeight(), getHeight() +

mTextHeightWithMaxLines -mTv.getHeight());

        }

animation.setFillAfter(true);

        animation.setAnimationListener(new Animation.AnimationListener() {

@Override

            public void onAnimationStart(Animation animation) {

applyAlphaAnimation(mTv, mAnimAlphaStart);

            }

@Override

            public void onAnimationEnd(Animation animation) {

// clear animation here to avoid repeated applyTransformation() calls

                clearAnimation();

                // clear the animation flag

                mAnimating =false;

                // notify the listener

                if (mListener !=null) {

mListener.onExpandStateChanged(mTv, !mCollapsed);

                }

}

@Override

            public void onAnimationRepeat(Animation animation) {

}

});

        clearAnimation();

        startAnimation(animation);

    }

@Override

    public boolean onInterceptTouchEvent(MotionEvent ev) {

// while an animation is in progress, intercept all the touch events to children to

// prevent extra clicks during the animation

        return mAnimating;

    }

@Override

    protected void onFinishInflate() {

super.onFinishInflate();

        findViews();

    }

@Override

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

// If no change, measure and return

        if (!mRelayout || getVisibility() == View.GONE) {

super.onMeasure(widthMeasureSpec, heightMeasureSpec);

return;

        }

mRelayout =false;

        // Setup with optimistic case

// i.e. Everything fits. No button needed

        mTextView.setVisibility(View.GONE);

        mTv.setMaxLines(Integer.MAX_VALUE);

        // Measure

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // If the text fits in collapsed mode, we are done.

        if (mTv.getLineCount() <=mMaxCollapsedLines) {

return;

        }

// Saves the text height w/ max lines

        mTextHeightWithMaxLines =getRealTextViewHeight(mTv);

        // Doesn't fit in collapsed mode. Collapse text view as needed. Show

// button.

        if (mCollapsed) {

mTv.setMaxLines(mMaxCollapsedLines);

        }

mTextView.setVisibility(View.VISIBLE);

        // Re-measure with new setup

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (mCollapsed) {

// Gets the margin between the TextView's bottom and the ViewGroup's bottom

            mTv.post(new Runnable() {

@Override

                public void run() {

mMarginBetweenTxtAndBottom = getHeight() -mTv.getHeight();

                }

});

            // Saves the collapsed height of this ViewGroup

            mCollapsedHeight = getMeasuredHeight();

        }

}

public void setOnExpandStateChangeListener(@Nullable OnExpandStateChangeListener listener) {

mListener = listener;

    }

public void setText(@Nullable CharSequence text) {

mRelayout =true;

        mTv.setText(text);

        setVisibility(TextUtils.isEmpty(text) ? View.GONE : View.VISIBLE);

    }

public void setText(@Nullable CharSequence text, @NonNull SparseBooleanArray collapsedStatus, int position) {

mCollapsedStatus = collapsedStatus;

        mPosition = position;

        boolean isCollapsed = collapsedStatus.get(position, true);

        clearAnimation();

        mCollapsed = isCollapsed;

        setText(text);

        getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;

        requestLayout();

    }

@Nullable

    public CharSequencegetText() {

if (mTv ==null) {

return "";

        }

return mTv.getText();

    }

private void init(AttributeSet attrs) {

TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ExpandableTextView);

        mMaxCollapsedLines = typedArray.getInt(R.styleable.ExpandableTextView_maxCollapsedLines, MAX_COLLAPSED_LINES);

        mAnimationDuration = typedArray.getInt(R.styleable.ExpandableTextView_animDuration, DEFAULT_ANIM_DURATION);

        mAnimAlphaStart = typedArray.getFloat(R.styleable.ExpandableTextView_animAlphaStart, DEFAULT_ANIM_ALPHA_START);

        typedArray.recycle();

        // enforces vertical orientation

        setOrientation(LinearLayout.VERTICAL);

        // default visibility is gone

        setVisibility(GONE);

    }

private void findViews() {

mTv = (TextView) findViewById(R.id.expandable_text);

        mTv.setOnClickListener(this);

        mTextView = (TextView) findViewById(R.id.expand_collapse);

        mTextView.setOnClickListener(this);

    }

private static boolean isPostHoneycomb() {

return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;

    }

private static boolean isPostLolipop() {

return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;

    }

@TargetApi(Build.VERSION_CODES.HONEYCOMB)

private static void applyAlphaAnimation(View view, float alpha) {

if (isPostHoneycomb()) {

view.setAlpha(alpha);

        }else {

AlphaAnimation alphaAnimation =new AlphaAnimation(alpha, alpha);

            // make it instant

            alphaAnimation.setDuration(0);

            alphaAnimation.setFillAfter(true);

            view.startAnimation(alphaAnimation);

        }

}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)

private static DrawablegetDrawable(@NonNull Context context, @DrawableRes int resId) {

Resources resources = context.getResources();

        if (isPostLolipop()) {

return resources.getDrawable(resId, context.getTheme());

        }else {

return resources.getDrawable(resId);

        }

}

private static int getRealTextViewHeight(@NonNull TextView textView) {

int textHeight = textView.getLayout().getLineTop(textView.getLineCount());

        int padding = textView.getCompoundPaddingTop() + textView.getCompoundPaddingBottom();

        return textHeight + padding;

    }

class ExpandCollapseAnimationextends Animation {

private final ViewmTargetView;

        private final int mStartHeight;

        private final int mEndHeight;

        public ExpandCollapseAnimation(View view, int startHeight, int endHeight) {

mTargetView = view;

            mStartHeight = startHeight;

            mEndHeight = endHeight;

            setDuration(mAnimationDuration);

        }

@Override

        protected void applyTransformation(float interpolatedTime, Transformation t) {

final int newHeight = (int) ((mEndHeight -mStartHeight) * interpolatedTime +mStartHeight);

            mTv.setMaxHeight(newHeight -mMarginBetweenTxtAndBottom);

            if (Float.compare(mAnimAlphaStart, 1.0f) !=0) {

applyAlphaAnimation(mTv, mAnimAlphaStart + interpolatedTime * (1.0f -mAnimAlphaStart));

            }

mTargetView.getLayoutParams().height = newHeight;

            mTargetView.requestLayout();

        }

@Override

        public void initialize(int width, int height, int parentWidth, int parentHeight) {

super.initialize(width, height, parentWidth, parentHeight);

        }

@Override

        public boolean willChangeBounds() {

return true;

        }

}

public interface OnExpandStateChangeListener {

/**

* Called when the expand/collapse animation has been finished

*

        * @param textView  - TextView being expanded/collapsed

        * @param isExpanded - true if the TextView has been expanded

*/

        void onExpandStateChanged(TextView textView, boolean isExpanded);

    }

}

这样就能简单的实现我们想要的效果  至于其他类似布局 仅仅在此基础上做稍微改动即可 

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

推荐阅读更多精彩内容