How to get length of first line in Edittext android? - android

I have a multi lines Edittext with a text (don't content "\n"), a font size (sp)
and the length of text > Edittext.width().
I want to get length of the first line in EditText.
How can I do it?
You can see the photo

One option could be to read the text and then get the index of the newline character, which is essentially the length of the string prior to it:
int firstLineLength = myEditText.getText().toString().indexOf("\n");
As an alternative, if you ever need to do this with other lines you can simply split the whole string based on the newline character:
String[] lines = myEditText.getText().toString().split("\n");
EDIT
Keep in mind that indexOf() will return -1 if an occurrence is not found. So if your EditText has one and only one string, you'll get a -1 line length so be prepared to check against that:
int lineEndIndex = myEditText.getText().toString().indexOf("\n");
int firstLineLength;
if(lineEndIndex == -1) {
firstLineLength = myEditText.getText().toString().length();
} else {
firstLineLength = lineEndIndex;
}

Related

Determine if content in editText is a "." ONLY

I have written a calculator type app. My mates found that entering single decimal points only into the editText's makes the app crash. Decimal numbers and integers work fine, but I get a number format exception when .'s are entered.
I want to check if a single . has been placed in an editText, in order for me to display a toast telling the user to stop trying to crash the app.
My issue is that a . doesn't have a numerical value...
You can wrap it in a try/catch which should be done anyway when parsing text. So something like
try
{
int someInt = Integer.parseInt(et.getText().toString());
// other code
}
catch (NumberFormatException e)
{
// notify user with Toast, alert, etc...
}
This way it will protect against any number format exception and will make the code more reusable later on.
You can treat .1 as 0.1 by the following.
String text = et.getText().toString();
int len = text.length();
// Do noting if edit text just contains a "." without numbers
if(len==0 || (len==1 && text.charAt(0).equals(".")))
return;
if(text.charAt(0).equals(".") && text.length() > 1) {
text = "0" + text;
}
// Do your parsing and calculations

Delete spaces from Editable object

I have deleted characters in edittext objects with this code
edit = etcalle.getEditableText();
if (edit.length() > 0)
edit.delete(edit.length() - 1, edit.length());
It has been working but when my string looks like this +81 901 it doesn't delete the space. It gets to it and stops deleting characters.
How can I remove the space in my text?
EDIT:
Just to be clear, I don't want to remove everything at once. Just one character at every time I hit my delete button
String original = etcalle.getText().toString();
then
etcalle.setText(original.substring(0,original.length-1));
of course be sure to check that the original is not null or length < 1
use this it will remove all the spaces
String str = "99 85263 9633";
str.replace(" ", ""); // Output is 99852639633
Then Its magic you can do this with this
String str = "99 85263 9633";
str.replaceFirst(" ",""); // Output is 9985263 9633

HTML Formatted String inserting into TextViews and EditText

All,
I have a database that will store an HTML tagged text to retain formatting information from an EditText. I create this string using HTML.toHtml(EditText.getText). I notice this method wraps whatever Spanned Text is put in it with <p> and </p>. The issue with that is when I got to use the method HTML.fromHtml(HTMLFormattedString) and then use the setText method of either a TextView or EditText there are two extra lines at the end of my actual text, which makes sense because that is how the paragraph tag works with HTML.
My question is is there anyway to make the textView or EditText shrink to not display the extra blank lines? What is the simplest way to do this? I have experimented with just removing the last <p> and </p>, but that only works if the user did not enter 3 or more new lines with the return key.
I ended up searching for white space at the end of the spanned text that was created and removed it. This took care of extra spaces due to the <p> </p> and was less time consuming than overriding the mentioned class to achieve the same results.
public SpannableStringBuilder trimTrailingWhitespace(
SpannableStringBuilder spannableString) {
if (spannableString == null)
return new SpannableStringBuilder("");
int i = spannableString.length();
// loop back to the first non-whitespace character
while (--i >= 0 && Character.isWhitespace(spannableString.charAt(i))) {
}
return new SpannableStringBuilder(spannableString.subSequence(0, i + 1));
}
Well this is just a round about approach. I had the same issue. And you are provided with two options,
1)As you said that paragraph tag works the way what you have suspected. What it does , it appends two "\n" values to the end of each <\p> tag. So you can convert the html to string and remove the last two characters which are usually two "\n"s
or
2) You have get into the Html Class itself. That is, you have to override the HTML class and look for handleP(SpannableStringBuilder text) and change its core logic a little bit.
private static void handleP(SpannableStringBuilder text) {
int len = text.length();
if (len >= 1 && text.charAt(len - 1) == '\n') {
if (len >= 2 && text.charAt(len - 2) == '\n') {
return;
}
text.append("\n");
return;
}
if (len != 0) {
text.append("\n\n");
}
}
As you can see here, it appends two "\n" in len!=0 which is were you have to do the change.

How do I get the text at a specific line in a TextView

I have a TextView that is X lines long. How do I get the text that is at, say, line 3?
Example: I have this TextView
This is line 1
And this is line 2
And this is line 3
I want to be able to get the String at any one of these lines by itself, such as getting the String at line 3 would return "And this is line 3". Searching for line breaks is not the solution I need, as it doesn't take into account text wrapping.
You can use textView.getLayout().getLineStart(int line) and getLineEnd to find the character offsets in the text.
Then you can just use textView.getText().substring(start, end) -- or subsequence if you are using Spannables for formatting/etc.
Here is some code to supplement the accepted answer:
List<CharSequence> lines = new ArrayList<>();
int count = textView.getLineCount();
for (int line = 0; line < count; line++) {
int start = textView.getLayout().getLineStart(line);
int end = textView.getLayout().getLineEnd(line);
CharSequence substring = textView.getText().subSequence(start, end);
lines.add(substring);
}

Android: Insert text into EditText at current position

I want to insert a constant string into an EditText by the press of a button. The string should be inserted at the current position in the EditText.
If I use EditText.append the text gets inserted at the end of the EditText.
How can I do that? I couldn't find a suitable method.
Cpt.Ohlund gave me the right hint. I solved it, now, partly with using EditText.getSelectionStart(), but I realized that you can also replace the selected text with the same expression and you don't need String.subString() for that.
int start = Math.max(myEditText.getSelectionStart(), 0);
int end = Math.max(myEditText.getSelectionEnd(), 0);
myEditText.getText().replace(Math.min(start, end), Math.max(start, end),
textToInsert, 0, textToInsert.length());
This works for both, inserting a text at the current position and replacing whatever text is selected by the user. The Math.max() is necessary in the first and second line because, if there is no selection or cursor in the EditText, getSelectionStart() and getSelectionEnd() will both return -1. The Math.min() and Math.max() in the third line is necessary because the user could have selected the text backwards and thus start would have a higher value than end which is not allowed for Editable.replace().
This seems simpler:
yourEditText.getText().insert(yourEditText.getSelectionStart(), "fizzbuzz");
However, Manuel's answer might be better if you want to replace any selected text with the inserted text.
Try using EditText.getSelectionStart() to get the current position of the cursor. Then you can use String.subString to get the text before and after the cursor and insert your text in the middle.
I think this function will help for you :
public void insertConstantStr(String insertStr) {
String oriContent = editText.getText().toString();
int index = editText.getSelectionStart() >= 0 ? editText.getSelectionStart() : 0;
StringBuilder sBuilder = new StringBuilder(oriContent);
sBuilder.insert(index, insertStr);
editText.setText(sBuilder.toString());
editText.setSelection(index + insertStr.length());
}
For Kotlin simply do that:
editText.text.insert(editText.selectionStart, "Your Text Here")
Editable editable = new SpannableStringBuilder("Pass a string here");
yourEditText.text = editable;

Categories

Resources