更新时间:2023-11-07 12:59:28
我用这个code,检查多少行,我的TextView,
I use this code to check how many lines in my textview,
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView1);
int totalLines = textView.getLineCount();
ViewTreeObserver vto = this.textView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
ViewTreeObserver obs = textView.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
System.out.println("Line Count is : " + textView.getLineCount());
}
});
}
}
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="300dp"
android:layout_height="500dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="I have a full-screen TextView holding a long Spanned that requires scrolling. The TextView's getLineCount() gives me the total number of lines used for the entire block of text but I'd like to know how many lines of text are currently visible on the screen. "
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
柜面您正在使用带有滚动一个TextView,你需要知道在屏幕上所显示的行数(不共线),
Incase you are using a Textview with scroll and you need to know the displayed line count on screen (not a total lines),
int height = myTextView.getHeight();
int scrollY = myTextView.getScrollY();
Layout layout = myTextView.getLayout();
int firstVisibleLineNumber = layout.getLineForVertical(scrollY);
int lastVisibleLineNumber = layout.getLineForVertical(scrollY+height);