How to delete the last letter from EditText with button?
Using substring() method , you can do it,
String str = myEditText.getText().toString();
str = str.substring ( 0, str.length() - 1 );
// Now set this Text to your edit text
myEditText.setText ( str );
you need to write above lines in onClick() method.
You can retrieve the text of EditText
and then get the sub-string
of that text and set again that text to EditText
as below...
String text = editText.getText().toString();
editText.setText(text.substring(0, text.length() - 1));
You can also use following procedure....it will be more efficient.
int length = editText.getText().length();
if (length > 0) {
editText.getText().delete(length - 1, length);
}
You should use switch-case
as below...and handle your nuttondel
onclick() as follows...
public class MainActivity extends Activity implements OnClickListener {
Button buttona, buttonb;
Button buttonDel;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
addListenerOnButton();
}
public void addListenerOnButton() {
buttona = (Button) findViewById(R.id.buttona);
buttona.setOnClickListener(this);
buttonb = (Button) findViewById(R.id.buttonb);
buttonb.setOnClickListener(this);
buttonDel = (Button) findViewById(R.id.buttondel);
buttonDel.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.buttona:
editText.setText(editText.getText().toString()+buttona.getText().toString());
break;
case R.id.buttonb:
editText.setText(editText.getText().toString()+buttonb.getText().toString());
break;
case R.id.buttondel:
int length = editText.getText().length();
if (length > 0) {
editText.getText().delete(length - 1, length);
}
break;
}
}
}