TextView最後一行,不完全顯示。截取顯示

1、效果圖大致如下:


本代碼存在的弊端是存放在listView中,可能出現需要滑動纔可以刷新,設置文本。 

可以使用:https://code.google.com/p/android-textview-multiline-ellipse/source/browse/

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import com.xingtuan.hysd.R;

/**
 * TextView的最後一行,不完全顯示文本。
 * Created by jiangp on 15/4/19.
 */
public class AutoTextView extends TextView {

    private int mEmptyWidth = 150;//空白文本寬度
    private int mMinLine = 2;

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

    public AutoTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.AutoTextView);
        int emptyWidth = (int) ta.getDimension(R.styleable.AutoTextView_atv_empty_width, 0);
        ta.recycle();
        if (emptyWidth > 0) {
            mEmptyWidth = emptyWidth;
        } else {
            mEmptyWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, mEmptyWidth, context.getResources().getDisplayMetrics());
        }
    }

    public void setAutoText(final CharSequence text) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        this.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                //可顯示文本區域的寬度
                int availableTextWidth = mMinLine * (getWidth() - getPaddingLeft() - getPaddingRight()) - mEmptyWidth;
                Paint paint = getPaint();
                paint.setTextSize(getTextSize());

                // 根據長度截取出剪裁後的文字
                String ellipsizeStr = (String) TextUtils.ellipsize(text, (TextPaint) paint, availableTextWidth, TextUtils.TruncateAt.END);
                setText(ellipsizeStr);
            }
        });
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章