Reputation: 2722
I am trying to remove\replace last line of a TextView
, but I want a way to do this faster.
For example I found this:
String temp = TextView.getText().toString();
temp.substring(0,temp.lastIndexOf("\n"));
But I want to do it faster without copy data from Textview to a string value and dont using Sting.lastIndexOf
(because its search in a string).
Can some one help me?
My Question isn't a dupplicate question becuase I want a way without using a string type!!!
Upvotes: -1
Views: 1498
Reputation:
Try this:
public String removeLastParagraph(String s) {
int index = s.lastIndexOf("\n");
if (index < 0) {
return s;
}
else {
return s.substring(0, index);
}
}
and use it like:
tv.setText(removeLastParagraph(tv.getText().toString().trim());
Upvotes: 0
Reputation: 9336
I suggest overwriting the TextView
class with your own implementation:
public class CustomTextView extends TextView{
// Overwrite any mandatory constructors and methods and just call super
public void removeLastLine(){
if(getText() == null) return;
String currentValue = getText().toString();
String newValue = currentValue.substring(0, currentValue.lastIndexOf("\n"));
setText(newValue);
}
}
Now you could use something along the lines of:
CustomTextView textView = ...
textView.removeLastLine();
Alternatively, since you seem to be looking for a one-liner without creating a String temp
for some reason, you could do this:
textView.setText(textView.getText().toString().replaceFirst("(.*)\n[^\n]+$", "$1"));
Regex explanation:
(.*) # One or more character (as capture group 1)
\n # a new-line
[^\n] # followed by one or more non new-lines
$ # at the end of the String
$1 # Replace it with the capture group 1 substring
# (so the last new-line, and everything after it are removed)
Upvotes: 3
Reputation: 4835
Use the System.getProperty("line.seperator")
instead of "\n"
public void removeLastLine(TextView textView) {
String temp = textView.getText().toString();
textView.setText(
temp.substring(0, temp.lastIndexOf(System.getProperty("line.seperator") )));
}
Upvotes: -1