[英]How to remove last line of TextView?
我正在嘗試刪除\\替換TextView
最后一行,但是我想要一種更快地執行此操作的方法 。 例如,我發現了這一點:
String temp = TextView.getText().toString();
temp.substring(0,temp.lastIndexOf("\n"));
但是我想更快地做到這一點,而無需將數據從Textview復制到字符串值,並且不要使用Sting.lastIndexOf
(因為它是在字符串中搜索)。
有人能幫我嗎?
我的問題不是重復的問題,因為我想要一種不使用字符串類型的方法!!!
我建議用您自己的實現覆蓋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);
}
}
現在您可以按照以下方式使用:
CustomTextView textView = ...
textView.removeLastLine();
另外,由於某種原因,您似乎正在尋找單線而不創建String temp
,因此可以這樣做:
textView.setText(textView.getText().toString().replaceFirst("(.*)\n[^\n]+$", "$1"));
正則表達式說明:
(.*) # 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)
使用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") )));
}
嘗試這個:
public String removeLastParagraph(String s) {
int index = s.lastIndexOf("\n");
if (index < 0) {
return s;
}
else {
return s.substring(0, index);
}
}
並像這樣使用它:
tv.setText(removeLastParagraph(tv.getText().toString().trim());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.