Is there a way to capture text once #
pressed until spacebar is pressed in EditText
? Thanks in advance for your help.
Asked
Active
Viewed 619 times
-1

DawidJ
- 1,245
- 12
- 19

Sukesh Saxena
- 201
- 2
- 18
-
2Have tried the text watcher interface on editText?https://developer.android.com/reference/android/text/TextWatcher – nyulan Jan 02 '19 at 08:12
-
Your question is difficult to understand. Do you mean you want to watch for the character '#' and then capture text until the spacebar is pressed? If so, I would recommend reading up on a text change listener (https://stackoverflow.com/questions/11134144/android-edittext-onchange-listener) – xrd Jan 02 '19 at 08:12
-
This is exactly what I wanna ask. Donno why downvoted. The query is simple and straightforward. Will check the link. – Sukesh Saxena Jan 02 '19 at 08:32
1 Answers
2
First attach addTextChangedListener
to your edittext
and call a method which will match a particular condition like below:
EditText editText = (EditText)findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
String capturedString = getText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
});
The above code will try to populate capturedString
everytime a new character is added to the edittext
field.
Now write another function getText()
like below:
public String getText(String s) {
String startChar = "#";
String endChar = " ";
String output = getStringBetweenTwoChars(s, startChar, endChar);
System.out.println(output);
}
This method will match the provided string for #
and space
. If found, it will return the captured string if not found, it will throw an error (This error will be captured in catch
block of the above code)
Now finally, write the below function which will intake a character sequence and two charecters and match the charecter sequence with the provided charecters and return the string between them:
public String getStringBetweenTwoChars(String input, String startChar, String endChar) {
try {
int start = input.indexOf(startChar);
if (start != -1) {
int end = input.indexOf(endChar, start + startChar.length());
if (end != -1) {
return input.substring(start + startChar.length(), end);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return input;
}
Hope this helps :)

Karthic Srinivasan
- 515
- 6
- 19