如何获取 TextView 中输入行的最大数?

如何获取 TextView 中输入行的最大数?

DisplayMetrics metrics = new DisplayMetrics ();
getWindowManager (). getDefaultDisplay (). getMetrics (metrics);
float width = metrics.widthPixels;
float height = metrics.heightPixels;

int lines = (int) (height / textView.getLineHeight ());

System.out.println (lines);
    TextView tv1 = (TextView) findViewById(R.id.tv1);
    tv1.setText("abcd\nhello\nworld123\n333333");
    tv1.post(new Runnable() {
        @Override
        public void run() {
            int lineCount    = tv1.getLineCount();
            Toast.makeText(MainActivity.this, "行数为:"+lineCount, Toast.LENGTH_LONG).show();
        }//行数为4
    });

这样也可以获取~

textview.getLineCount()

请参考:documentation
看下这个方法能解决你的问题吗:

Paint paint = new Paint();
Rect bounds = new Rect();

int text_height = 0;
int text_width = 0;

paint.setTypeface(Typeface.DEFAULT);// your preference here
paint.setTextSize(25);// have this the same as your text size

String text = "Some random text";

paint.getTextBounds(text, 0, text.length(), bounds);

text_height =  bounds.height();
text_width =  bounds.width();

注意:tv1.getLineCount()的调用不能直接在 tv1.setText() 之后,这样返回的结果会是0,
可以在setText之后使用Handler发送一个消息,然后在Handler中去调用tv1.getLineCount()
这样才能获取到值