判斷文字是否超長的方法java
public static void showOrHideContent(TextView content,TextView btn,int maxLines,String btntext){ Layout layout = content.getLayout(); if (layout != null) { int lineCount = layout.getLineCount(); if (lineCount > maxLines) { btn.setText(btntext); btn.setVisibility(View.VISIBLE); } else { int ellipsisCount = layout.getEllipsisCount(lineCount - 1);//小米note2下返回0 if (ellipsisCount > 0) { btn.setVisibility(View.VISIBLE); } else { btn.setVisibility(View.GONE); } } } else { ViewTreeObserver observer = content.getViewTreeObserver(); if (observer.isAlive()) { observer.addOnPreDrawListener( new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { Layout layout = content.getLayout(); if (layout != null) { int lineCount = layout.getLineCount(); if (lineCount > maxLines) {//小米note2的兼容處理 btn.setVisibility(View.VISIBLE); } else { int ellipsisCount = layout.getEllipsisCount(lineCount - 1);//小米note2下返回0 if (ellipsisCount > 0) { btn.setVisibility(View.VISIBLE); } else { btn.setVisibility(View.GONE); } } } try { (content.getViewTreeObserver()).removeOnPreDrawListener(this); } catch (Exception e) { e.printStackTrace(); } return true; } } ); } } }
調用方式:android
content爲現實內容的textview,btn爲展開或者收起的按鈕,5爲textview最大顯示行數app
StringUtils.showOrHideContent(content,btn,5,"查看全文");
btn的監聽事件:ide
btn.setOnClickListener(v -> { if(!isAll){ content.setMaxHeight(getResources().getDisplayMetrics().heightPixels); btn.setText("收起"); isAll = true; }else{ content.setMaxLines(5); btn.setText("查看所有"); isAll = false; } });
xml文件:this
<TextView android:id="@+id/content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/name" android:layout_below="@+id/name" android:layout_marginRight="@dimen/app_margin" android:layout_marginTop="13sp" android:ellipsize="end" android:maxLines="5" android:text="贍養費的給附表轉是多少贍養費的給附表轉是多少贍養費的給附表轉是多少贍養費的給附表轉是多少贍養費的給附表轉是多少贍養費的給附表轉是多少贍養費的給附表轉是多少贍養費的給附表轉是多少贍養費的給附表轉是多少贍養費的給附表轉是多少贍養費的給附表轉是多少" android:textColor="@color/black" android:textSize="15sp" />