I have an EditText which is supposed to have multi-line while typing and should have an action done when enter is pressed, meaning the soft keyboard should disappear and the cursor made invisible... basically the EditText should lose "focus".
Now this is done and working, but the problem is that the "enter" key leaves a new line in the EditText.
I have tried to remove it by setting the entire text to "", but the EditText is blank with a new line.
I have tried to remove it by replacing '\n' with a 's' and setting the text back, but the text starts in a new line.
String cap = caption.getText().toString().replace('\n', 's').trim();
caption.setText(cap);
Thanks in advance.
I know this is a late answer but maybe it can help someone.
I recently had this problem and I solved it by implementing an addTextChangedListener to my EditText.
Code:
EditText editText = new EditText(this);
layout.addView(editText);
editText.addTextChangedListener(new TextWatcher() {
boolean ignore = false; // This is used to prevent infinite recursion in the afterTextChanged method
#Override
public void afterTextChanged(Editable arg0) {
if (ignore) return;
ignore = true;
String s = arg0.toString();
if (s.length() > 0) {
// The condition checks if the last typed char's ASCII value is equal to 10, which is the new line decimal value
if (((int)(s.charAt(s.length()-1)) == 10)) {
String newStr = s.substring(0, s.length()-1); // Removes the new line character from the string
editText.setText(newStr);
editText.setSelection(editText.length()); // Sets the text cursor to the end of the text
}
}
ignore = false;
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
There might be better ways to get rid of the new line character, but this worked for me and seems simple enough.
Related
I want to allow user to enter only 10 characters inside the EditText. I tried two approaches.
Approach 1:
android:maxLength="10"
Approach 2:
I used InputFilter class.
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
When I am using these approaches, the cursor stops at 10 and no more characters are visible. However, it is still taking the characters I type after those 10 characters. I can see them in the suggestion area above keyboard. To explain clearly let me take an example.
Suppose I entered "abcdefghij", it works fine. Now, suppose I entered "abcdefghijklm", I can see only first 10 characters in the EditText but when press backspace it removes last character "m" instead of removing "j", the last character visible in EditText.
How can I solve this problem? I dont want to keep the extra characters in buffer also. So that when user presses backspace it should delete the 10th character.
You can use edittext.addTextChangedListener.
editTextLimited.addTextChangedListener(new TextWatcher() {
/** flag to prevent loop call of onTextChanged() */
private boolean setTextFlag = true;
#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) {
// add your code here something like this
if(count > 10){
Toast.makeText(context,"10 chars allowed",Toast.LENGTH_LONG).show();
// set the text to a string max length 10:
if (setTextFlag) {
setTextFlag = false;
editTextLimited.setText(s.subSequence(0, 10));
} else {
setTextFlag = true;
}
}
}
});
Your problem should be solved by adding this to your EditText:
android:inputType="textFilter"
In my tablet app I have used fragments and one fragment has multiple Edittexts, and I have a linear layout which will add a sublayout as many times the user wishes to add, in that fragment
This sublayout has two edittext, both this edittext is having
addtextchangelistener(Textwatcher) and
onfocuschangelistner
every time the text is changed 3 conditions are checked in both the edittext
every time the focus is changed 2 conditions are checked in both the edittext
After doing all this condition check, the problem I'm facing is, the edittext typing is too slow, its like i type an email and the whole email gets completely typed after 5 secs or more,
This is the code for 1 edit text in the sublayout:
receiverName.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View paramView, boolean hasFocus) {
receivernameFocus = hasFocus;
if(hasFocus)
{
if(receiverName.getText().toString().length()>0)
ReceiverName_btn_cancel.setVisibility(View.VISIBLE);
else
ReceiverName_btn_cancel.setVisibility(View.INVISIBLE);
}
else
ReceiverName_btn_cancel.setVisibility(View.INVISIBLE);
}
});
receiverName.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence paramCharSequence, int paramInt1,int paramInt2, int paramInt3) {
if(receivernameFocus)
{
if(receiverName.getText().toString().length()>0)
{
receiverNamePresent = true;
ReceiverName_btn_cancel.setVisibility(View.VISIBLE);
}
else
{
receiverNamePresent = false;
ReceiverName_btn_cancel.setVisibility(View.INVISIBLE);
}
}
else
ReceiverName_btn_cancel.setVisibility(View.INVISIBLE);
if(receiverEmailPresent && receiverNamePresent)
addReceiver.setBackgroundResource(R.drawable.plus_receiver);
else
addReceiver.setBackgroundResource(R.drawable.plus_deselect_receiver);
}
#Override
public void beforeTextChanged(CharSequence paramCharSequence,
int paramInt1, int paramInt2, int paramInt3) {
}
#Override
public void afterTextChanged(Editable paramEditable) {
}
});
same conditions are present for the other edittext, and everytime the user inflate another view, same set of edittext will be created for the new view too.
I can't remove the conditions, all of them are necessary, and you can see its just some button visibility or setting background resource
How to optimize this code, or how to speed up the edittext typing speed for android tablet?
EDIT: If I'm typing 10 letters persecond its showing only 1 letter per second in the edittext(so all the 10 letters will be visible in the edittext after 10 seconds), which I believe is happening because of multiple condition checking within onTextChanged method, the delay in showing the text is too much for user experience.
How to make the edittext show the text as fast as I'm typing it
Thanks
Here public void onTextChanged(CharSequence paramCharSequence, int paramInt1,int paramInt2, int paramInt3) it's generally in this format:
public void onTextChanged(CharSequence s, int start, int before, int count)
So here you will need to do some operation using paramInt3 . If you would like to show suggest text will come after you enter 3 letter then perform an operation here in this manner:
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (count%3 == 1)
{
adapter.clear();
GetPlaces task = new GetPlaces();
task.execute(dep_place.getText().toString());
}
}
here I haved updated text from server side in background. You just need to modify this portion from where your text will come use this code here.
Thanks.
Here is my scenario,
I just wanna get only number and a particular special character like $ at the end of the EditText field.
Ex: 234.34$
I don't wanna validate after entering this input, but rather user can only enter decimal number and at the end this special character.
Some one please help me to do this.
you can use the following (progromatically)
ed.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
ed.setKeyListener(DigitsKeyListener.getInstance("0123456789.$"));
you can define whatever characters you want within the DigitsKeyListener.getInstance
or if dont want the user to enter the $ sign and you want to be entered manually after the user finishes editting...
#Override
protected OnFocusChangeListener getOnFocusChangeListener() {
return new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
//Member variable in the class which contains an EditText
CurrencyTextbox.this.hadFocus = true;
} else {
// Thes EditText has lost focus
Log.v(TAG, "Lost focus.");
if (CurrencyTextbox.this.hadFocus) {
// We previously had focus, now we lost it, format the user input!
// Get current value of the Textbox
String value = CurrencyTextbox.this.textbox.getText().toString();
// Formatting the user input
value = String.format(//Doing some formatting);
// Reset the had focus
CurrencyTextbox.this.hadFocus = false;
}
}
}
};
Use this in your EditText android:inputType="numberDecimal"
In the Class file add a TextWatcher to the EditText as following code and in the method afterTextChanged(Editable s) add "$" at the end of the text in EditText.
EditText input = (EditText) findViewById(R.id.search_text_box);
input.addTextChangedListener(onInputTextChanged);
public TextWatcher onInputTextChanged = new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
// Add "$" at the end of text in EditText
}
};
In the Edit text add the property android:inputType="numberDecimal"
You can accept only numbers and phone number type using java code
EditText number1 = (EditText) layout.findViewById(R.id.edittext);
number1.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
number1.setKeyListener(DigitsKeyListener.getInstance("Replace with your special characters”));
This code will avoid lot of validations after reading input
I'm using a AutoCompleteTextView, the default behavior of the backspace button goes something like this.
Say i type "Ar", this gives me a suggestion "Argentina", i select "Argentina" from the drop down...The Text now becomes "Argentina ". But say i need to remove the last character, so I hit backspace on the keyboard, the AutcompleteTextView removes all the text till the point i typed (ie. the text now becomes "Ar" again).
How do i eliminate this behavior and let the text in the AutoComplete to behave normally?
At first I thought it was some kind of SpannableString so i called "clearSpans()" but it doesn't seem to work. Any pointers?
Thanks in advance. :)
I think you use the MultiAutoCompleteTextView which add the setTokenizer(new SpaceTokenizer()).
If you use
AutoCompleteTextView instead of MultiAutoCompleteTextView and remove the setTokenizer(...)
the problem will be gone.
I did not find any solution, but finally I figured out, this code worked for me:
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
// removing QwertyKeyListener.Replaced span
Editable text = editText.getText();
Object[] spans = text.getSpans(0, text.length(), Object.class);
if (spans != null) {
for (int i = spans.length - 1; i >= 0; i--) {
Object o = spans[i];
String desc = "" + o; // This is a hack, not a perfect solution, but works. "QwertyKeyListener.Replaced" is a private type
if (desc.indexOf("QwertyKeyListener$Replaced") != -1) {
text.removeSpan(o);
}
}
}
} catch (Throwable e) {
MyUtil.msgError(e);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
I have a TextWatcher set on an EditText that changes the input type after a user types a number followed by a space.
If the user types two numbers the input type switches and accepts the next character, but if the user types only one number and presses space the input type still changes but it won't accept the first character the user tries to input.
I've tested this on Froyo and 1.6, it only happens on Froyo, 1.6 works like it should.
Here's the code:
TextWatcher watcher = new TextWatcher() {
#Override
public void afterTextChanged (Editable s) {
}
#Override
public void beforeTextChanged (CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged (CharSequence s, int start, int before, int count) {
// Parsed text holder is a class that just parses the EditText and pulls out various parts.
ParsedTextHolder th = parseTextHolder(s);
String newText = "";
Boolean setTextKeyListener = false;
String tGetTextString = mQuery.getText().toString();
if (!th.pFullMatch.equals("")) {
if (th.pFullMatch.length() == 2) {
mQuery.setKeyListener(new
TextKeyListener(TextKeyListener.Capitalize.SENTENCES, true));
newText = tGetTextString + " for ";
setTextKeyListener = true;
}
}
if (setTextKeyListener) {
Log.i("setTextKeyListener", "true");
if (mQuery.getKeyListener().getClass() != TextKeyListener.class) {
mQuery.setKeyListener(new TextKeyListener(TextKeyListener.Capitalize.SENTENCES, true));
} else {
Log.d("setTextKeyListener", "skipped. already was text.");
}
if (!newText.equals("")) {
int position = newText.length();
String ttext = newText;
newText = "";
mQuery.setText(ttext, TextView.BufferType.EDITABLE);
mQuery.setText(ttext);
Editable text = mQuery.getEditableText();
Log.w("setting selectiont to text: ", text.toString());
Log.w("setting selectiont to position: ", Integer.toString(position));
Selection.setSelection(text, position);
mQuery.setKeyListener(new TextKeyListener(TextKeyListener.Capitalize.SENTENCES, true));
}
}
}
};
Also, here's an APK if you want to see what the bug is like: http://endlesswhileloop.com/files/KeyboardBug.apk
Is mQuery the editText that is being watched? According to the javadocs, you shouldn't be making any changes to the text in your EditText in onTextChanged. All such changes should be made in afterTextChanged.
Generally, I've ended up examining the change in onTextChanged and then doing the work that results form the change in afterTextChanged. You might try that.