how to remove character from edittext? - android

I want to know is there any method by which i can remove the specific character from the EditText. I want to remove charter from EditText by specifying position in edit text
is there something like removeAt() for EditText?
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button b1=(Button)findViewById(R.id.button1);
final EditText ed1=(EditText)findViewById(R.id.editText1);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
//i want something like this
ed1.removeAt(5);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
EXTRA INFORMATION
the main problem is i want to make text bold inside edittext but not all the text. The text that is typed after setting bold button on(bold is my toggle button).
ok here is the code
ed1.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
int i = 0;
switch(event.getAction())
{
case KeyEvent.ACTION_UP:
if(bold.isChecked())
{
i=ed1.getSelectionStart();
ed1.append(Html.fromHtml("<b>"+ed1.getText().toString().charAt(i-1)+"</b>"));
}
return true;
}
return false;
}
});
the problem is that i get double character's one is normal character and then again the bold one so i want to remove that normal characters by specifying there position

You have to change it to string first because getText returns editable, e.g:
int charIndex;
String text = ed1.getText().toString();
text = text.substring(0, charIndex) + text.substring(charIndex+1);
ed1.setText(text);
To remove a Character and keep the BOLD characters the same :
ed1.setText((Spanned)ed1.getText().delete(indexStart , indexEnd));
This will remove the Characters from index "indexStart" to "indexEnd -1".
e.g. if you use delete(0,1); it will delete the first Character.
I hope that helps :)

My Implementation is given below. I hope it will be helpful
int cursorPosition = mDialerEditText.getSelectionStart();
if (cursorPosition > 0) {
mDialerEditText.setText(mDialerEditText.getText().delete(cursorPosition - 1, cursorPosition));
mDialerEditText.setSelection(cursorPosition-1);
}

EditText is just like any other TextView, but it can also be edited. Therefore you can use the getText() method, store it as a String, remove the desired char, and call setText(str) method on the EditText to change the text.

Get the input from the EditText and store in a String.
String temp = ed1.getText().toString();
Now manipulate this String temp to remove the character at the desired position.
(I suggest you use String.substring(..) function to achieve this.)
Lastly, set the manipulated string temp in the EditText.
ed1.setText(temp);

Related

determine which EditText field is selected on focus

I have a table with multiple rows, each containing an EditText which corresponds to a dimension. I want to have some sort of listener that will return whichever EditText is currently selected. Can this be done with getCurrentFocus(); or onFocusChange();?
My idea is to have the user select/focus the dimension field they want edited, and then completing the field using an output slope/angle from the device's gyroscope when a "write data" button is pressed. I'd probably do this using selected_dimension_edittext.setText(gyro_value);
You can know which EditText has Focus by the ID of the view like this:
EditText edText1 = (EditText)findViewById(R.id.editText1);
EditText edText2 = (EditText)findViewById(R.id.editText2);
OnFocusChangeListener mFocusChangeListener = new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(hasFocus){ //Check if View has focus
switch (v.getId()){
case R.id.editText1: {
//Code A
} break;
case R.id.editText2: {
//Code B
} break;
}
}
}
};
edText1.setOnFocusChangeListener(mFocusChangeListener);
edText2.setOnFocusChangeListener(mFocusChangeListener);
If the editTexts are in a ArrayList you could pass a Tag to each editText which is the index.
For example:
for(int i=0;i<editTextList.size();i++){
editTextList.get(i).setTag(i);
}
Then you can check with a listener (textChangedListener or TextWatcher-->http://lecturesnippets.com/android-textchanged-listener-textwatcher/) which EditText is changed or selected by reading the tag. Just iterate through your editTextList and call the setText()-Method if the edit text has the selected tag.

how to start an activity automtically when user input a value to textfield in android(Like keyup event.)?

i want to enter a value to a text field and once i enter i want it to view something on a text view automatically.. how to do that in android.??
this is what i tried.
txt.setKeyListener(new KeyListener() {
#Override
public boolean onKeyUp(View v, Editable e, int i, KeyEvent k) {
// TODO Auto-generated method stub
if(i==40)
{
TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText("Done");
}
return false;
}
Take your input value in an EditText. Compare your EditText's value and accordingly change your TextView. I don't see any use of onKeyUp method.
Or if you really want to use onKeyUp method, I guess this link might help you!

get selection handles programmatically in android

In my app I have EditText element but I use it like TextView (it is not editable).
I want to select all text in this field by click on some button.
I do it with the next code
Selection.setSelection((Spannable) et.getText(),0, et.getText().length());
et.setSelected(true);
It works fine and text selected but after that I can not change ends of selection.
How can I call selection handles programmatically?
Also I blocked OnLongClick because I need only Copy option and add it in custom button.
You need to make sure that the EditText has the property android:textIsSelectable="true" in the layout file.
You can also do the same thing by
et.setTextIsSelectable(true);
But please make sure that your application's minSdkVersion is 11 to use this.
Try some thing like this
et.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
int strt= et.getSelectionStart();
int end = et.getSelectionEnd();
Log.i(" Selectionm",et.getText().toString().substring(strt, end));
return false;
}
});
With required android:textIsSelectable="true", call the following method with EditText or TextView as parameter:
private fun forceSelectionWithHandlesVisible(view: TextView) {
if (!view.hasSelection()) {
view.performLongClick()
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
// Hack required to make the selection handles visible when focus programmatically
val event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_UP, 0F, 0F, 0)
with(event) {
view.onTouchEvent(this)
recycle()
}
}
}
Worked for me.

I need to configure a multiline edit text but never leave a newline ENTER [duplicate]

How do I make an EditText on Android such that the user may not enter a multi-line text, but the display is still multi-line (i.e. there is word-wrap instead of the text going over to the right)?
It's similar to the built-in SMS application where we can't input newline but the text is displayed in multiple lines.
I would subclass the widget and override the key event handling in order to block the Enter key:
class MyTextView extends EditText
{
...
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode==KeyEvent.KEYCODE_ENTER)
{
// Just ignore the [Enter] key
return true;
}
// Handle all other keys in the default way
return super.onKeyDown(keyCode, event);
}
}
This is a method, where you don't have to override the EditText class. You just catch and replace the newlines with empty strings.
edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
/*
* The loop is in reverse for a purpose,
* each replace or delete call on the Editable will cause
* the afterTextChanged method to be called again.
* Hence the return statement after the first removal.
* http://developer.android.com/reference/android/text/TextWatcher.html#afterTextChanged(android.text.Editable)
*/
for(int i = s.length()-1; i >= 0; i--){
if(s.charAt(i) == '\n'){
s.delete(i, i + 1);
return;
}
}
}
});
Credit to Rolf for improvement on an earlier answer.
Property in XML
android:lines="5"
android:inputType="textPersonName"
This one works for me:
<EditText
android:inputType="textShortMessage|textMultiLine"
android:minLines="3"
... />
It shows a smiley instead of the Enter key.
Here's a more correct answer that does not display the enter key on the IME keyboard:
// IMPORTANT, do this before any of the code following it
myEditText.setSingleLine(true);
// IMPORTANT, to allow wrapping
myEditText.setHorizontallyScrolling(false);
// IMPORTANT, or else your edit text would wrap but not expand to multiple lines
myEditText.setMaxLines(6);
Also, you may replace setSingleLine(true) with either, an explicit android:inputType on the XML layout file, or setInputType(InputType.*) on code – in which, the input type used, is anything that you know restricts the input to single lines only (i.e., anything that calls setSingleLine(true) implicitly already).
Explanation:
What setSingleLine(true) does is calling setHorizontallyScrolling(true) and setLines(1) implicitly, alongside with altering some IME keyboard settings to disable the enter key.
In turn, the call to setLines(1) is like calling setMinLines(1) and setMaxLines(1) in one call.
Some input types (i.e., the constants from InputType.TYPE_*) calls setSingleLine(true) implicitly, or at least achieves the same effect.
Conclusion:
So to achieve what the OP wants, we simply counter those implicit settings by reverting those implicit calls.
The answer provided by #Andreas Rudolph contains a critical bug and shouldn't be used. The code causes an IndexOutOfBoundsException when you past text inside the EditText which contains multiple new-line characters. This is caused by the type of loop which is used, the Editable object will call the afterTextChanged method as soon as its contents change (replace, delete, insert).
Correct code:
edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
/*
* The loop is in reverse for a purpose,
* each replace or delete call on the Editable will cause
* the afterTextChanged method to be called again.
* Hence the return statement after the first removal.
* http://developer.android.com/reference/android/text/TextWatcher.html#afterTextChanged(android.text.Editable)
*/
for(int i = s.length()-1; i >= 0; i--){
if(s.charAt(i) == '\n'){
s.delete(i, i + 1);
return;
}
}
}
});
I'm testing this and it seems to work:
EditText editText = new EditText(context);
editText.setSingleLine(false);
editText.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_EMAIL_SUBJECT);
Try this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER)
{
//Nothing
return true;
}
return super.onKeyDown(keyCode, event);
}
You can set it from the xml like this:
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="10"
don't forget android:inputType="text", if you don't set it, it doesn't work. I don't know why though.
Also don't forget to change maxLines to your preferred value.
Simply add
android:singleLine="true"
to your EditText
Here is the solution....
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="150"
android:textSize="15dp"
android:imeOptions="actionDone"
android:inputType="text|textMultiLine"/>
Usage in java class
editText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_ENTER)
{
// Just ignore the [Enter] key
return true;
}
// Handle all other keys in the default way
return (keyCode == KeyEvent.KEYCODE_ENTER);
}
});
The accepted answer worked so well until I copied text with line-breaks into into the EditText. So I added onTextContextMenuItem to monitor the paste action.
#Override
public boolean onTextContextMenuItem(int id) {
boolean ret = super.onTextContextMenuItem(id);
switch (id) {
case android.R.id.paste:
onTextPaste();
break;
}
return ret;
}
public void onTextPaste() {
if (getText() == null)
return;
String text = getText().toString();
text = text.replaceAll(System.getProperty("line.separator"), " ");
text = text.replaceAll("\\s+", " ");
setText(text);
}
You can change the action button from code
editText.imeOptions = EditorInfo.IME_ACTION_DONE
editText.setRawInputType(InputType.TYPE_CLASS_TEXT)
Xml
android:inputType="textMultiLine"
<EditText
android:id="#+id/Msg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:lines="5"
android:selectAllOnFocus="true"
android:hint="Skriv meddelande...\n(max 100tkn)"/>
EditText et = (EditText)findViewById(R.id.Msg);
String strTmp = et.getText().toString();
strTmp = strTmp.replaceAll("\\n"," ");
EditText textView = new EditText(activity);
...
textView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if(KeyEvent.KEYCODE_ENTER == keyEvent.getKeyCode()) {
return false;
}
.......
}
});
For a URI you could use:
android:inputType="textUri"
android:lines="1"
android:maxLength="128"
Otherwise android:inputType="textPersonName" as mentioned above works for other EditText such user name, etc.
I will give another option so you don't have to subclass EditText. Create an InputFilter that filters out linebreaks. Then use EditText.addInputFilter.
Source code for such an input filter is here: https://gist.github.com/CapnSpellcheck/7c72830e43927380daf5205100c93977
You can pass 0 in the constructor, and it won't allow any newlines. Also, you can combine this with one of the other tweaks such as android:imeOptions="actionDone", as this will help improve the experience on some devices.
Adding this property to the EditText XML works for me:
android:lines="1"
It lets the users input newline characters but the EditText itself does not increase in height.

Prevent enter key on EditText but still show the text as multi-line

How do I make an EditText on Android such that the user may not enter a multi-line text, but the display is still multi-line (i.e. there is word-wrap instead of the text going over to the right)?
It's similar to the built-in SMS application where we can't input newline but the text is displayed in multiple lines.
I would subclass the widget and override the key event handling in order to block the Enter key:
class MyTextView extends EditText
{
...
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode==KeyEvent.KEYCODE_ENTER)
{
// Just ignore the [Enter] key
return true;
}
// Handle all other keys in the default way
return super.onKeyDown(keyCode, event);
}
}
This is a method, where you don't have to override the EditText class. You just catch and replace the newlines with empty strings.
edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
/*
* The loop is in reverse for a purpose,
* each replace or delete call on the Editable will cause
* the afterTextChanged method to be called again.
* Hence the return statement after the first removal.
* http://developer.android.com/reference/android/text/TextWatcher.html#afterTextChanged(android.text.Editable)
*/
for(int i = s.length()-1; i >= 0; i--){
if(s.charAt(i) == '\n'){
s.delete(i, i + 1);
return;
}
}
}
});
Credit to Rolf for improvement on an earlier answer.
Property in XML
android:lines="5"
android:inputType="textPersonName"
This one works for me:
<EditText
android:inputType="textShortMessage|textMultiLine"
android:minLines="3"
... />
It shows a smiley instead of the Enter key.
Here's a more correct answer that does not display the enter key on the IME keyboard:
// IMPORTANT, do this before any of the code following it
myEditText.setSingleLine(true);
// IMPORTANT, to allow wrapping
myEditText.setHorizontallyScrolling(false);
// IMPORTANT, or else your edit text would wrap but not expand to multiple lines
myEditText.setMaxLines(6);
Also, you may replace setSingleLine(true) with either, an explicit android:inputType on the XML layout file, or setInputType(InputType.*) on code – in which, the input type used, is anything that you know restricts the input to single lines only (i.e., anything that calls setSingleLine(true) implicitly already).
Explanation:
What setSingleLine(true) does is calling setHorizontallyScrolling(true) and setLines(1) implicitly, alongside with altering some IME keyboard settings to disable the enter key.
In turn, the call to setLines(1) is like calling setMinLines(1) and setMaxLines(1) in one call.
Some input types (i.e., the constants from InputType.TYPE_*) calls setSingleLine(true) implicitly, or at least achieves the same effect.
Conclusion:
So to achieve what the OP wants, we simply counter those implicit settings by reverting those implicit calls.
The answer provided by #Andreas Rudolph contains a critical bug and shouldn't be used. The code causes an IndexOutOfBoundsException when you past text inside the EditText which contains multiple new-line characters. This is caused by the type of loop which is used, the Editable object will call the afterTextChanged method as soon as its contents change (replace, delete, insert).
Correct code:
edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
/*
* The loop is in reverse for a purpose,
* each replace or delete call on the Editable will cause
* the afterTextChanged method to be called again.
* Hence the return statement after the first removal.
* http://developer.android.com/reference/android/text/TextWatcher.html#afterTextChanged(android.text.Editable)
*/
for(int i = s.length()-1; i >= 0; i--){
if(s.charAt(i) == '\n'){
s.delete(i, i + 1);
return;
}
}
}
});
I'm testing this and it seems to work:
EditText editText = new EditText(context);
editText.setSingleLine(false);
editText.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_EMAIL_SUBJECT);
Try this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER)
{
//Nothing
return true;
}
return super.onKeyDown(keyCode, event);
}
You can set it from the xml like this:
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="10"
don't forget android:inputType="text", if you don't set it, it doesn't work. I don't know why though.
Also don't forget to change maxLines to your preferred value.
Simply add
android:singleLine="true"
to your EditText
Here is the solution....
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="150"
android:textSize="15dp"
android:imeOptions="actionDone"
android:inputType="text|textMultiLine"/>
Usage in java class
editText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
if (keyCode==KeyEvent.KEYCODE_ENTER)
{
// Just ignore the [Enter] key
return true;
}
// Handle all other keys in the default way
return (keyCode == KeyEvent.KEYCODE_ENTER);
}
});
The accepted answer worked so well until I copied text with line-breaks into into the EditText. So I added onTextContextMenuItem to monitor the paste action.
#Override
public boolean onTextContextMenuItem(int id) {
boolean ret = super.onTextContextMenuItem(id);
switch (id) {
case android.R.id.paste:
onTextPaste();
break;
}
return ret;
}
public void onTextPaste() {
if (getText() == null)
return;
String text = getText().toString();
text = text.replaceAll(System.getProperty("line.separator"), " ");
text = text.replaceAll("\\s+", " ");
setText(text);
}
You can change the action button from code
editText.imeOptions = EditorInfo.IME_ACTION_DONE
editText.setRawInputType(InputType.TYPE_CLASS_TEXT)
Xml
android:inputType="textMultiLine"
<EditText
android:id="#+id/Msg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:lines="5"
android:selectAllOnFocus="true"
android:hint="Skriv meddelande...\n(max 100tkn)"/>
EditText et = (EditText)findViewById(R.id.Msg);
String strTmp = et.getText().toString();
strTmp = strTmp.replaceAll("\\n"," ");
EditText textView = new EditText(activity);
...
textView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if(KeyEvent.KEYCODE_ENTER == keyEvent.getKeyCode()) {
return false;
}
.......
}
});
For a URI you could use:
android:inputType="textUri"
android:lines="1"
android:maxLength="128"
Otherwise android:inputType="textPersonName" as mentioned above works for other EditText such user name, etc.
I will give another option so you don't have to subclass EditText. Create an InputFilter that filters out linebreaks. Then use EditText.addInputFilter.
Source code for such an input filter is here: https://gist.github.com/CapnSpellcheck/7c72830e43927380daf5205100c93977
You can pass 0 in the constructor, and it won't allow any newlines. Also, you can combine this with one of the other tweaks such as android:imeOptions="actionDone", as this will help improve the experience on some devices.
Adding this property to the EditText XML works for me:
android:lines="1"
It lets the users input newline characters but the EditText itself does not increase in height.

Categories

Resources