简体   繁体   中英

Getting text of the last line of TextView Android development

I'm working on a calculator app in android studio, and I would the calculator to append the answer to the existing equation, more like a graphing calculator, where it shows the equation then the answer beneath it. My current solution works for the first equation only. I've tried

int start = display.getLayout().getLineStart(display.getLineCount());
int end = display.getLayout().getLineEnd(display.getLineCount());

then

double result = calc(display.getText().toString().substring(start,end));

The result is that I get an IndexOutOfBoundsException from getLineEnd, and I don't know how to go about it?

Ticked answer is wrong. I have multiline TextView but the text has no '\\n' or '\\r' characters. It is multiline because width isn't enough for whole text. Your problem is you sending getLineCount() as parameter you must send getLineCount() -1 for last line. I am calculating last line width as below:

float lastLineWidth = textViewMessage.getLayout().getLineRight(textViewMessage.getLineCount() - 1) - textViewMessage.getLayout().getLineLeft(textViewMessage.getLineCount() - 1);

But I have one problem with using it. I cant call textView.getLayout() method in ListView.getView() mehtod. It always returns null. I can only call it in TextView.Post() method but I don't want to call it in Post() method because I do some adding and removing rules to LayoutParams and it causes problem scroll problems in ListView.

Is there a way to get last line string or last line width without calling getLayout() method of TextView.

Sounds like you have a multiline TextView so you could try splitting by new line chars and getting the last element from resulting array like this:

public static String getLastLine(TextView display){
    String lines[] = display.getText().toString().split("\\r?\\n");
    String lastOne = lines[lines.length-1];
    return lastOne;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM