我有一个扩展TextView的customTextView。
我想覆盖setText,这样如果某个文本长度大于最大行数,那么我必须显示一些其他文本而不是getText中的文本。
这是我的代码
public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setLinksClickable(true);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
String text = String.valueOf(getText());
Spanned htmlFormatedText = OmniTextUtil.getHyperLinked(text);
setText(htmlFormatedText);
List<CharSequence> charSequenceList = getLines(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
if(getLineCount() > getMaxLines())
{
for(int i =0; i < getMaxLines(); i++)
{
text = text + charSequenceList.get(i);
}
text = text.substring(0, text.length() -3) + "...";
setText(text);
}
}
}
public static List<CharSequence> getLines(TextView view) {
final List<CharSequence> lines = new ArrayList<>();
final Layout layout = view.getLayout();
if (layout != null) {
// Get the number of lines currently in the layout
final int lineCount = layout.getLineCount();
// Get the text from the layout.
final CharSequence text = layout.getText();
// Initialize a start index of 0, and iterate for all lines
for (int i = 0, startIndex = 0; i < lineCount; i++) {
// Get the end index of the current line (use getLineVisibleEnd()
// instead if you don't want to include whitespace)
final int endIndex = layout.getLineEnd(i);
// Add the subSequence between the last start index
// and the end index for the current line.
lines.add(text.subSequence(startIndex, endIndex));
// Update the start index, since the indices are relative
// to the full text.
startIndex = endIndex;
}
}
return lines;
}
}
II可以设置我的文字,但滚动它再次成为普通文本......
答案 0 :(得分:-1)
如果您只想在文本末尾添加三条虚线,那么您可以简单地完成。尝试以下代码
//编程
text_view.setEllipsize(TextUtils.TruncateAt.END);
text_view.setMaxLines(2);//set number of line what ever you want.
text_view.setText("your long text");
//使用xml
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:lines="2"
android:maxLines="2"
android:text="your long text"
android:textColor="@android:color/black" />
如果您想检查文字是否过长,请尝试link。希望它能为您提供帮助。