Category:Android UI
Article From:https://www.cnblogs.com/ganchuanpu/p/6618995.html

On the basis of Android native TextView, TextView:PhilExpandableTextView can be contracted / expanded.
Implementation principle: the core is to control the max lines of TextView. In the initialization stage of TextView, but when View is not yet drawn, ViewTreeObserver is used to monitor onPreDraw events and get TextVie.W normally displays the number of lines that need to be displayed, but only the number of rows (less than the total number of lines) is set for the maximum run of the TextView, resulting in the contraction summary effect of TextView, and the maximum number of TextView rows is set to the normal display when the user extends through a button or other way.The total number of rows +1 (+1 is to maintain the margin, to avoid insufficient).

public class MainActivity extends Activity {
    private String str = "";

    protected void onCreate(Bundle savedInstanceState) {

        for (int i = 0; i < 200; i++) {
            str = str + i + "  ";
        final ExpandableTextView etv = (ExpandableTextView) findViewById(R.id.etv);

        Button btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                boolean b = etv.getExpandablestatus();

                b = !b;





package com.ganchuanpu.ExpandableTextView;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.TextView;
import android.widget.Toast;

public class ExpandableTextView extends TextView {

    // Maximum line, default display 3 linesPrivate Final int MAX = 3;/ / complete number of rows neededPrivate int lines;Private ExpanDableTextView mExpandableTextView;Private Boolean expandablestatus = false;/ / construct method with two parametersPublic ExpandableTextView (Context context, AttributeSet attrs) {Super (context, attrs);MExpandableTextView = this;Init ();}Private void init () {/ / at vIew before drawing, before onDrawViewTreeObserver mViewTreeObserver = this.getViewTreeObserver ();MViewTreeObserver.addOnPreDrawListener (New OnPreDrawListener () {@OverridePublic Boolean onPreDraw () {/ / avoid repeated listenerMExpandableTextView.getViEwTreeObserver ().RemoveOnPreDrawListener (this);/ / obtain the number of rowsLines = GeTLineCount ();Return true;}});SetExpandable (false);}Whether or not to expand or contract,/ / true, unfolded;/ / false, not unfoldingPublic void setExpandable (Boolean isEx)Pand) {If (isExpand) {SetMaxLines (lines + 1);} elseSetMaXLines (MAX);Expandablestatus = isExpand;}Public Boolean getExpandablestatus () {Return expandablestatus;}}


Link of this Article: Scalable textview

Leave a Reply

Your email address will not be published. Required fields are marked *