[英]How to remove last line of TextView?
I am trying to remove\\replace last line of a TextView
, but I want a way to do this faster . 我正在尝试删除\\替换
TextView
最后一行,但是我想要一种更快地执行此操作的方法 。 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). 但是我想更快地做到这一点,而无需将数据从Textview复制到字符串值,并且不要使用
Sting.lastIndexOf
(因为它是在字符串中搜索)。
Can some one help me? 有人能帮我吗?
My Question isn't a dupplicate question becuase I want a way without using a string type!!! 我的问题不是重复的问题,因为我想要一种不使用字符串类型的方法!!!
I suggest overwriting the TextView
class with your own implementation: 我建议用您自己的实现覆盖
TextView
类:
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: 另外,由于某种原因,您似乎正在寻找单线而不创建
String temp
,因此可以这样做:
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)
Use the System.getProperty("line.seperator")
instead of "\\n" 使用
System.getProperty("line.seperator")
代替“ \\ n”
public void removeLastLine(TextView textView) {
String temp = textView.getText().toString();
textView.setText(
temp.substring(0, temp.lastIndexOf(System.getProperty("line.seperator") )));
}
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.