I have been reading the answers from the post How to set cursor position in EditText? I do have a specific problem in my EditText which might be the cause of the problem. In my xml layout, I define an EditText called "edit" whose inputType = none. According to the android developer documents, if the inputType = none, the text in not editable. The reason why is "none" is caused this is the way I prevent the android general keyboard from popping up over my User-Interface , which works very well.
I want to do something like this: user entered : 5 + sin( ) , now the cursor editText cursor position should be right after the ) symbol, but there's no cursor shown since the inputType = none. What I need to do is move the position of where the next text input will be placed in between the ( ) symbols. What happens is that the next text input goes right after the ) symbol.
So if the next text input is 4, then: 5 + sin( )4 , I don't want this. I rather have the following: 5 + sin(4 )
I am using a custom made keyboard which has the button "( )". Here's what I have tried without any success:
//once the user presses the "( )" button:
Selection.setSelection(edit.getText(),edit.getText().length() - 2);
Another way I have tried:
//once the user presses the "( )" button:
edit.setInputType(InputType.TYPE_CLASS_NUMBER);
edit.setSelection(edit.getText().length() - 2);
edit.setInputType(InputType.TYPE_NULL);
Neither of the two ways has worked for me. I've also tried to set the inputType of the editText to something else besides "none" on the xml file. But, the android keyboard pops up on top of my custom made keyboard.
Any thoughts or ideas would be helpful
I don't know how exactly does your () button work but you can give a try this one.
yourEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if( s.length()>0 && s.charAt(s.length()-1) == ')' ){
yourEditText.setSelection(s.length()-1);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
Related
I have been having issues with some odd behaviours from the EditText .setSelection that I am hoping you can all help with!
The app I am working on has a search field and there is the need to have it behave very similar to a browser search bar. For example, if the user types "fo", we would want the EditText to autocomplete to "foobar" with the autocompleted "obar" text highlighted so it can be easily replaced by the user incase the autocomplete does not match what the user was intending to type.
To accomplish this, I have an EditText field with a TextWatcher setup to try to autocomplete the text afterTextChanged. The following is my code:
editText.addTextChangedListener(new TextWatcher() {
int lastCount = 0;
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable editable) {
editText.removeTextChangedListener(this);
String searchString = editable.toString();
if (editable.length() > lastCount) {
lastCount = editable.length();
int oldLength = searchString.length();
String autoFillResult = completeAutofill(searchString);
if (!autoFillResult.equals("")) {
searchString = autoFillResult;
editable.clear();
editable.append(autoFillResult);
editText.setSelection(oldLength, autoFillResult.length());
}
} else lastCount = editable.length();
editText.addTextChangedListener(this);
}
});
My issue is as follows. Using the previous "Foobar" case:
The user types "F", the EditText autofills "oobar" and highlights it.
Then the user types the first "o"
The EditText field is momentarily cleared (i.e. afterTextChanged receives an Editable with the empty string)
The EditText correctly autofills to user supplied "Fo" followed by autocompleted "obar" which is highlighted.
The issue is the EditText is being cleared then repopulated when the user types the next character, which creates a noticeable disturbance in the EditText field. Interestingly, I have singled out the editText.setSelection(oldLength, autoFillResult.length()); as the culprit (i.e. commenting out the line gets rid of the issue, but obviously its the wrong functionality).
After completing some Google research and my own debugging I am still unsure why this is happening. The issue does not appear excessively common as I could not find it on Google and I could not figure out the reason for this issue in my own experimentation.
Thank you in advance!
the if condition should possibly be:
autoFillResult != null && !autoFillResult.equals("")
while you might be looking for (or attempting to recreate) an AutoCompleteTextView.
Try removing editable.clear();
This question already has answers here:
Put constant text inside EditText which should be non-editable - Android
(18 answers)
Closed 2 years ago.
I'm quite new to android development and when working on my company project, I encounter a problem.
I need an Edittext with fixed suffix as part of the Edittext so that when user type in, the suffix will wrap to new line just like normal content of the Edittext, but user can not edit and select this suffix part.
I have search around and can't find a good solution for this problem. Some suggest to add a drawable contains text to right of edittext, but this solution will not make the suffix part wrap to new line when people type in.
Another possible solution is to handle text change for the edittext but this will lead to very complicated handle for the cursor of edittext(like handle text-hint and user selection gesture, ...)
So my question is: Is there anyone have implement something like this or can someone point me some directions to easily implement this feature for edittext.
Here is dirty solution to your problem.
Lets assume you have an EditText called mEditText, a String called SUFFIX, and a boolean addedSuffix:
boolean addedSuffix = false;
String SUFFIX = " my suffix";
EditText mEditText = (EditText) findViewById(R.id.my_edit_text);
attach a textWatcher to your EditText
mEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// if the only text is the suffix
if(s.toString().equals(SUFFIX)){
mEditText.setText(""); // clear the text
return;
}
// If there is text append on SUFFIX as long as it is not there
// move cursor back before the suffix
if(s.length() > 0 && !s.toString().contains(SUFFIX) && !s.toString().equals(SUFFIX)){
String text = s.toString().concat(SUFFIX);
mEditText.setText(text);
mEditText.setSelection(text.length() - SUFFIX.length());
addedSuffix = true; // flip the addedSuffix flag to true
}
}
#Override
public void afterTextChanged(Editable s) {
if(s.length() == 0){
addedSuffix = false; // reset the addedSuffix flag
}
}
});
Like i said this is a quick and dirty solution, so this only adds the suffix when the user actually types into the EditText field. If you need it to be added before the user starts typing you can modify the logic to do so on your own.
Good luck and Happy Coding!
Please try this code on your edittext's onfocuschangedlistener.
your suffix value added when your focuschangelistener not focused or focusing on other fields.
//sdur is my edittext name
sdur.setOnFocusChangeListener(View.OnFocusChangeListener { v, hasFocus ->
if (!hasFocus) {
if((!sdur.text.toString().endsWith("mins")&&(sdur.text.toString().isNotEmpty()))){
var jj=sdur.text.toString()
sdur.setText("$jj mins")
}
// code to execute when EditText loses focus
}
});
Intro:
I am currently trying to implement an input method for an EditText for my Crossword Puzzle where the user sees something like "____" in the EditText. The underscores mark missing letters, the first char entered will fill the first underscore.
Of course other cells in the puzzle might be solved already, so the EditText text could be "ST_CKOV_RF_OW". I had all this functionality already in my own input view, a subclass of view with an overridden onDraw(). This worked pretty well, except that the view won't appear on some lower Android versions and the Back key slipped through my input routine and wasn't accessible.
So I thought I'd do it with EditText, implement a TextWatcher and be fine, but I can't get it to work properly. What I have right now is working, I can use the keyboard to enter letters, but again the Backspace isn't working, and of course if the user touches into the EditText the position gets messed up.
public void beforeTextChanged(CharSequence s,int start,int count, int after){
et.removeTextChangedListener(textWatcher);
int position = text.indexOf("_");
if(position==-1) onAnswerEntered(et.getText().toString().replace("_", "")); //finished
else {
et.setSelection(et.getText().toString().indexOf("_"));
et.addTextChangedListener(textWatcher);
}
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
et.removeTextChangedListener(textWatcher);
try {
String currentKey = s.toString().substring(start, start+1);
Logger.log("Current Key", currentKey);
int position = text.indexOf("_");
Logger.log("Current Position _ ", position+"");
//replace _ with key
String sbefore=text.substring(0, position);
String safter=text.substring(position+1, text.length());
text=sbefore+currentKey+safter;
int positionNext = text.indexOf("_");
Logger.log("Next Position _ ", positionNext+"");
if(positionNext==-1) onAnswerEntered(et.getText().toString().replace("_","")); //finished
else {
et.setText(text);
et.setSelection(et.getText().toString().indexOf("_"));
et.addTextChangedListener(textWatcher);
}
} catch(IndexOutOfBoundsException ioobe) {
ioobe.printStackTrace();
}
}
I also tried to set an OnKeyListener, but it won't work on EditText (I can get backspace event, nothing else)
So maybe I am totally on the wrong track, but please help me and give me a clue to how I can accomplish my goal. Thanks.
I gave up on it and implemented a simple but working kind of hack. I receive input in my (hidden) EditText now, the output goes to the visible TextView, a function in between fills the "_" with the input from the EditText.
Ex.
hint = "A_A_A_A"
edittext input = "BBB"
textview shows "ABABABA"
Moving an app from 2.2 to 3.x, one of my EditText's that I was using a TextWatcher on for validation is behaving badly. In short, when a user clicks on the EditText and the entire word goes into 'suggestions mode' (where it is underlined), it effectively gets removed from the EditText from the TextWatcher's perspective, triggering my text validation check that I do for an empty EditText. The code:
mText = (EditText) findViewById(R.id.inpt_title);
mText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable editable) {
final String title = editable.toString();
Log.d(LOG_TAG, "addTextChangedListener(): title: " + title + ", length: " + title.length());
if (title.length() == 0) {
// empty title
mText.setError(getString(R.string.error_note_title_empty));
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
mText.setTextColor(getResources().getColor(R.color.black));
}
#Override
public void onTextChanged(CharSequence s, int start, int count, int after) {}
});
I'd like to keep suggestions working, but there seems to be some weird interaction here.
Any way to either a) keep the EditText from being empty when the entire word is in 'suggestion mode', or at least checking to see if the EditText is in the 'suggestion' state to determine if the EditText is truly empty, or b) turing off suggestions? I've tried android:inputType="text|textCapWords|textNoSuggestions" for the EditText in question, as well as setting it via mText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); in the code above but suggestions keep happening on a Lenovo 3.1 tablet.
Update:
I see API 14 added a isInputMethodTarget() method to the EditText, which I could use to check for active suggestions and disable the validation... but I am running against API 12. Perhaps I could check the IME directly to see if the suggestions are active?
I want to cause the focus of one edit text box to move to another on editting (meaning you can only type on letter before it automatically moves on to the next edit text).
It's the "on edit" that I can't get my head around. Can anyone help me out with a simple example? Theres a lot I need to implement it into, so just a basic understanding should set the ball rolling ^_^
I do not really recommend this. With soft keyboards and multiple languages, what exactly is "one letter"? After all, a soft keyboard might enter in an entire word, like it or not.
CommonsWare makes an excellent point: you can't prevent the user from adding more characters to the EditText box, however you can listen to what's changed and act on that. Here's how to:
EditText editbox = (EditText) findViewById(R.id.MyEditBoxName);
editbox.addTextChangedListener(new TextWatcher()
{
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
public void afterTextChanged(Editable s)
{
// Test s for length, request focus for the next edit.
// editbox2.requestFocus();
}
});
Be careful not to get yourself into an infinite loop changing the editbox, any changes you make will cause these methods to be called again recursively.