Extract a line from an EditText

♀尐吖头ヾ 提交于 2019-12-01 03:14:08

问题


How can we extract a line from a multiLine EditText ?

I tried this way, but I know that is not a good practice :

String street1 = "";
String street2 = "";
EditText streetEt = ((EditText) findViewById(R.id.street));
ExtractedText extractedText = new ExtractedText();
ExtractedTextRequest req = new ExtractedTextRequest();
int endOfLineOffset = 0;

req.hintMaxLines = 1;
streetEt.extractText(req, extractedText);
endOfLineOffset = extractedText.partialEndOffset;
street1 = extractedText.toString();
...

is there an easier way to do this like looking for \n in the string ?


回答1:


Try using String.split(). Code example:

String multiLines = streetEt.getText().toString();
String[] streets;
String delimiter = "\n";

streets = multiLines.split(delimiter);

Now you have an array of streets.

Let's say, for example, your EditText reads "1st St.\nHighway Rd.\nUniversity Ave." (or is those 3 streets separated by line breaks, instead of you actually seeing \n). Following the code example I provided you,

  • multiLines becomes "1st St.\nHighway Rd.\nUniversity Ave."
  • streets = multiLines.split(delimiter); fills the array streets with the street names, i.e.

    • streets[0] = "1st St."
    • streets[1] = "Highway Rd."
    • streets[2] = "University Ave."



回答2:


Try this:

String text = streetEt.getText();

String firstLine = text.substring(0,text.indexOf("\n"));



回答3:


Try this,

String text=editText1.getText().toString().replace("\n", " ").trim();


来源:https://stackoverflow.com/questions/11247253/extract-a-line-from-an-edittext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!