如何获取textView可以在Android中显示的数字行

时间:2012-08-24 09:39:47

标签: android textview

我想知道textView可以显示的数字行。 我可以在一行中获得数字字符

int maxVisibleChars =  textView.getPaint().breakText(text,
                    true, textView.getMeasuredWidth(), null);

但是我不知道textView可以正确显示多少行 因为我的textView调整大小取决于屏幕分辨率 我需要知道这一点。谢谢

1 个答案:

答案 0 :(得分:7)

我使用此代码检查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&apos;s getLineCount() gives me the total number of lines used for the entire block of text but I&apos;d like to know how many lines of text are currently visible on the screen. "
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

如果你正在使用带滚动的Textview,你需要知道屏幕上显示的行数(不是总行数),

int height    = myTextView.getHeight();
int scrollY   = myTextView.getScrollY();
Layout layout = myTextView.getLayout();

int firstVisibleLineNumber = layout.getLineForVertical(scrollY);
int lastVisibleLineNumber  = layout.getLineForVertical(scrollY+height);