Created
September 19, 2016 06:01
-
-
Save daolq3012/ea1179dcfe71fa1a6f87af9e539f1167 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.lab.dmm.okan.ui; | |
import android.content.Context; | |
import android.util.AttributeSet; | |
import android.view.ViewTreeObserver; | |
import android.widget.TextView; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
/** | |
* Created by le.quang.dao on 19/09/2016. | |
*/ | |
public class EllipsizeTextView extends TextView { | |
private static final String REPLACER = "…"; | |
private final ViewTreeObserver.OnGlobalLayoutListener mListener; | |
/** | |
* @param context Context | |
*/ | |
public EllipsizeTextView(Context context) { | |
this(context, null); | |
} | |
/** | |
* @param context Context | |
* @param attrs AttributeSet | |
*/ | |
public EllipsizeTextView(Context context, AttributeSet attrs) { | |
this(context, attrs, 0); | |
} | |
public EllipsizeTextView(Context context, AttributeSet attrs, int defStyleAttr) { | |
super(context, attrs, defStyleAttr); | |
mListener = new ViewTreeObserver.OnGlobalLayoutListener() { | |
@Override | |
public void onGlobalLayout() { | |
forceMultiLineEllipsize(); | |
getViewTreeObserver().removeOnGlobalLayoutListener(mListener); | |
} | |
}; | |
} | |
@Override | |
public void setText(CharSequence text, BufferType type) { | |
super.setText(text, type); | |
if (mListener != null) { | |
this.getViewTreeObserver().addOnGlobalLayoutListener(mListener); | |
} | |
} | |
private void forceMultiLineEllipsize() { | |
int maxLines = Math.min(getMaxLines(), getHeight() / getLineHeight()); // 現在は3 | |
if (getLineCount() > maxLines) { | |
int lineEndIndex = getLayout().getLineEnd(maxLines - 1); | |
if (getText().length() <= lineEndIndex) { | |
lineEndIndex = getText().length() - 1; | |
} | |
String theLastCharOnTheLastIndex = String.valueOf(getText().charAt(lineEndIndex)); | |
boolean isTheLastCharOnTheLastIndexASCII = isAnASCII(theLastCharOnTheLastIndex); | |
if (isTheLastCharOnTheLastIndexASCII) { | |
lineEndIndex -= 1; | |
} | |
final String text2 = getText().subSequence(0, lineEndIndex - REPLACER.length()) + REPLACER; | |
setText(text2); | |
} | |
} | |
private static boolean isAnASCII(String str) { | |
Pattern pattern = Pattern.compile("^[\\p{ASCII}]$"); | |
Matcher matcher = pattern.matcher(str); | |
return matcher.find(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment