I have a simple activity. Only one edittext and one button.After writing some text in the edittext if I press the button I want to delete the last character of the text.
I have tried like this:
String backSpace = txtMsg.getText().toString();
if(!backSpace.equals(""));
String mystring=backSpace.substring(0, txtMsg.length()-1));
txtMsg.setText("");
txtMsg.append(mystring);
It works fine but I want to manually append the backspace character at last position and finally at any position by moving the cursor(by txtMsg.setSelection());
Like we append any character to the end of the text:
txtMsg.append("C");
I want to know what will be in place of C for appending the backspace?Please Help
Thanks in advance.
I am not sure if you still need an answer to this or not, but I recently had the same need as you and I used the delete methond on the Editable android type:
http://developer.android.com/reference/android/text/Editable.html#delete(int,%20int)
I had a password EditText and did the following in the click handler for the 'delete' button:
// delete
if (m_userPass.getText().length() > 0) {
m_userPass.getText().delete(m_userPass.getText().length() - 1,
m_userPass.getText().length());
}
The delete method takes two arguments, the start and end position of the text to delete. In my example, I am just making the delete button delete the last character (regardless of the cursor). If you wanted to get fancier, you could put in logic to figure out the start and end position based on the cursor position.
The start position has to come before the end position (I accidentally made that mistake at first). And the start position has to be greater than or equal to zero.
there is a simple way of doing what you want via:
KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
input.dispatchKeyEvent(event);
You can try this, it worked for me:
if(!(text.length()==0))
text.setText(text.getText().delete(text.length() - 1, text.length()));
Related
Actually I want to delete all text in a text field, and I am using a loop calling device.press('KEYCODE_DEL') to achieve this.
But there are two disadvantages:
Not efficient enough, especially when I don't know how many
characters in the text field so I need set a large enough loop
Need to move the cursor to the end before deleting
So I am trying to accomplish this by two steps:
select all text
press delete button
I found an similar question here which is not solved yet.
And there is an answer for how to select all text, but I think it has the same issues as my loop delete way.
I did several tests, and found a way close to it:
device.press('KEYCODE_MENU', 'MonkeyDevice.DOWN', '')
device.press('KEYCODE_A')
device.press('KEYCODE_MENU', 'MonkeyDevice.UP', '')
I thought these three steps accomplish a MENU+A operation. But it did not work every time. I executed this code for 20 times(in a loop) and found it only took effect for about 5-8 times.
Besides, I found these three steps will move the cursor to the first place most of the time.
Did anyone know why is this operation not reliable? Or any other suggestions to select all text?
Appreciate for any suggestions!
AndroidViewClient's EditText has a method for that:
def setText(self, text):
"""
This function makes sure that any previously entered text is deleted before
setting the value of the field.
"""
if self.text() == text:
return
self.touch()
guardrail = 0
maxSize = len(self.text()) + 1
while maxSize > guardrail:
guardrail += 1
self.device.press('KEYCODE_DEL', adbclient.DOWN_AND_UP)
self.device.press('KEYCODE_FORWARD_DEL', adbclient.DOWN_AND_UP)
self.type(text, alreadyTouched=True)
Using AndroidViewClient its pretty easy. Try this code-
editText= vc.findViewByIdOrRaise(EDITTEXT ID in quotes)
(x,y) = editText.getXY()
editText.device.drag((x,y), (x,y), 2000, 1)
vc.dump()
device.press('KEYCODE_DEL')
I made a custom keyboard for android. When I press backspace button of my keyboard I use
getCurrentInputConnection().deleteSurroundingText(1, 0);
to delete one letter from the input field. But when I select some text and then press the backspace button, the selected text is not deleted. What method in input connection should I use so that selected text is also deleted from my keyboard when I press the backspace button?
When deleting you need to take into account the following situations:
There is a composing selection.
The editor/user has a cursor selection on the text.
There is no selection of any kind.
If there is a selection then it should be deleted. If there is no selection then the character in front of the cursor should be deleted.
Solution 1
At first I used this method. I like it because it only uses the input connection.
CharSequence selectedText = inputConnection.getSelectedText(0);
if (TextUtils.isEmpty(selectedText)) {
// no selection, so delete previous character
inputConnection.deleteSurroundingText(1, 0);
} else {
// delete the selection
inputConnection.commitText("", 1);
}
As long as the input connection is using the default BaseInputConnection.deleteSurroundingText method, this should be fine. However, it should be noted that the documentation warns
IME authors: please be careful not to delete only half of a surrogate
pair. Also take care not to delete more characters than are in the
editor, as that may have ill effects on the application.
If some custom view is using an input connection that doesn't correctly check for for text length or surrogate pairs, then this could cause a crash. Even though this is an unlikely senario, if you use this solution, then you should add that extra checking code here.
This may be why the sample Android keyboard first checks if there is a composing span, and if there isn't then it using the following solution.
Solution 2
You can also use the input connection to send a KeyEvent with KEYCODE_DEL. In my opinion this is not as good because it is a soft keyboard masquerading as a hard keyboard. But many keyboards do this. When I was making a custom view that accepted keyboard input, I had to handle deletes as a KeyEvent, that is, independently of the input connection (because the input connection was not deleting the text).
So just send the delete message as a KeyEvent (as if you were pressing a hard keyboard key down and then letting it up).
getCurrentInputConnection().sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_DEL));
getCurrentInputConnection().sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,KeyEvent.KEYCODE_DEL));
This works as expected. It will delete the selection if there is one, or delete one character behind the cursor if there isn't a selection. (However, you should handle any composing span separately.)
Thanks to this answer for the idea.
Call getCurrentInputConnection().commitText("",1);
i know highlighting in text-view is possible
Highlight Textview Using EditText
and scrolling text-view is also possible
(got the scroll code from here and is successfully scrolling too)
textView scroll at first line
now the question is, i am searching and i want to highlight that text and navigate to it, when someone presses the search button, the highlighting part is perfect, now i can get the index of the word in the string, but not line number of the string in the text-view,
point is if i want to find a position of certain text in text-view, i.e. which line number is that on, how to do it ?
i found an answer for this, but later i realized its for iOS
Search occurrences of a string in a TextView
Correct if I am wrong, you want to know the position where a particular text is in a String? If so then you can do it by using the following
String text = "0123hello9012hello8901hello7890";
String word = "hello";
Log.d("startOfWordPosition",text.indexOf(word)); // prints "4"
Log.d("endOfWordPosition",text.lastIndexOf(word)); // prints "22"
As you see that it will tell you the position as to where the word is located but you have to think about case where a word may come more than once. If you are sure that word will occur only once then above code is perfect for you. If not, then you will have to somehow tackle the problem.
This is working for loading a file into a textview so that the user's last selection or cursor position is at the top of the screen.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
page.setSelection(pos, pos2);
Layout layout = page.getLayout();
scroll.scrollTo(0, layout.getLineTop(layout.getLineForOffset(pos2))); }
}, 500);
page is a TextView, pos and pos2 are ints and the two ends of the last selection by the user (they are the same int if it's just the cursor), scroll is a scrollview containing the textview. It is all in a Handler because of delay issues internal to Android's loading all these objects. Th filename, pos and pos2 are saved as settings on exit.
I do backspace in textfield, and i need to set as composingText word or it part, that has left before cursor position. I must do that thing each time when i press backspace. So my step must be:
get size of last word (or part of it);
make it as composing text.
I try do it like this:
ic.setSelection(startWordPosition, word.length());
ic.setComposingText(word, 1);
All works good, while i don't test backspace in string like "a.a". It select all 3 characters, but when set, replace only part after dot.
Then i try make it like this:
ic.deleteSurroundingText(word.length(),0);
ic.setComposingText(word, 1);
But it not work correctly and delete sometimes text before my word(maybe because it currently compose).
Just find one more way that looks like right:
ic.finishComposingText();
ic.deleteSurroundingText(word.length(),0);
ic.setComposingText(word, 1);
ic.setSelection(fullInputedString.length(),fullInputedString.length());
Is it correct?
How should it be in right way?
target sdk=8
Thanks!
UPD:
I found next solution for
ic.finishComposingText();
ic.deleteSurroundingText(wordForInsert.length(), 0);
ic.setComposingText(wordForInsert, 1);
And for latest android version i use appropriate method:
ic.setComposingRegion();
But this solution provide issue in standatrd android browser for 4.0v Android and latest.
i have an edit text in my activity.i am entering numbers in it manually but
int mystart = destinationNumber.getSelectionStart();
int myend = destinationNumber.getSelectionEnd();
numberText.getText().replace(Math.min(mystart, myend), Math.max(mystart, myend),
"1", 0, 1);
its entering fine according to the cursor position.
i have a delete button in my acitivity which deletes single character according to cursor postion.
numberText.getText().delete(myend - 1, mystart);
But this logic is not working properly when i select whole text and call delete method it gives me IndexOutOfBoundsException OR i select 4-5 digits and call this delete.
I want the same functionality as android contact dialpad number enter field.Can someone help me figure out what is the correct logic to delete single digit from edittext and multiple selected digits as well.
Thanks
delete receives the start as first parameter and end as second, not the other way around.
Probably the error its taht mystart or myend(probably this) are bigger or smoller than numberText.lenght().
Try to put a Log.d("","" ) with the lenght of the text, mystart and myend and check if you need a myend -1 or something like that.