如何获得数行一个TextView在Android的显示如何获得、TextView、Android

2023-09-08 08:47:43 作者:╰つ被忽略的一种角色、

我想知道一些行一个TextView可以显示。我可以得到一些字符在一行

I want to know number line a textView can display. i can get the number character in one line

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

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

But i don't know how many line my textView can display properly Because my textView resize depend on screen resolution. I need to know that. Thank you

推荐答案

我用这个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&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,你需要知道在屏幕上所显示的行数(不共线),

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);