有时候业务需要 , textview文本内容是一行以内是一种操作 , 超出一行是另外一种操作 . 这里记录下怎么判断textview的文本内容是否超出一行的方法.
效果图:
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ctsFligthCardStatus"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"
>
<TextView
android:id="@+id/tv1"
android:layout_width="200dp"
android:layout_height="50dp"
android:background="#fadfad"
android:gravity="center_vertical"
android:typeface="monospace"
tools:text="《三体》是刘慈欣创作的系列长"/>
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
tools:text="超出一行"/>
</LinearLayout>
代码:
package com.eg.lyx.shiqu;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextPaint;
import android.view.ViewTreeObserver;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView tv1;
private TextView tv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
ViewTreeObserver vto2 = tv1.getViewTreeObserver();
vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
TextPaint mTextPaint = tv1.getPaint();
mTextPaint.setTextSize(tv1.getTextSize());
int mTextViewWidth = (int) mTextPaint.measureText("《三体》是刘慈欣创作的系列长篇");
tv1.setText("《三体》是刘慈欣创作的系列长篇");
if (mTextViewWidth > tv1.getWidth()) {//超出一行
tv2.setText("超出一行");
} else {
tv2.setText("未超出一行");
}
}
});
}
}