by clicking on the cancel button, each letter in the edit text is removed.
// click listener
btncancel.setOnClickListener(view -> {
String remove = txt.getText().toString();
if(!TextUtils.isEmpty(remove)){
remove = remove.substring(0, remove.length() - 1); //clearing one by one
txt.setText(remove); }
txt.clearFocus();
});
CodePudding user response:
I'm not sure what the question is but as the title suggests, if you want to do it using back button, you can override method called onBackPressed(), remove the super call and run your code.
CodePudding user response:
this is very simple solution to do that
// click listener
btncancel.setOnClickListener(view -> {
txt.setText(removeLastChar(txt.getText().toString()));
}
});
public String removeLastChar(String s) {
if (s.length() > 0) {
return s[0..-1]
}
return s
}
CodePudding user response:
100% it's will work for you..
@Override
public void onBackPressed() {
removeLastChar(binding.tvName);
}
public void removeLastChar(TextView s) {
if (s.length() > 0) {
String remove = s.getText().toString();
if(!TextUtils.isEmpty(remove)){
remove = remove.substring(0, remove.length() - 1);
s.setText(remove); }
s.clearFocus();
}else{
super.onBackPressed();
}
}