I'm a beginner in Android Studio, and I want to make a C button in calc with 2 functions.
How do I do that on one tap the C button erases only one number, and on hold erase all numbers in TextView?
findViewById(R.id.btnClear).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtScreen.setText(""); // Clear the screen
// Reset all the states and flags
lastNumeric = false;
stateError = false;
lastDot = false;
You can set an onClickListener and onLongClickListener to achieve this.
cButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String currentText = textView.getText().toString();
if(currentText.length >= 2){
currentText = currentText.substring(0, currentText.length - 2);
}else{
currentText = "";
}
textView.setText(currentText);
}
});
cButton.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
textView.setText("");
return true;
}
});
Have you looked in to the onClick() and onLongPress() methods?
cancelButton.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
myTextView.setText("");
return true;
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
removeOneCharacter();
}
});
private void removeOneCharacter()
{
String textViewValue = myTextView.getText().toString();
if (textViewValue != null && textViewValue.length >= 2)
{
myTextView.setText(textViewValue.substring(0, textViewValue.length() - 2);
}
}
The onClick() method removes on char from the TextView at a time. The onClick() method however removes the entire String from the TextView but only considering if there is already 2 or more characters to prevent an Exception from occurring due to the upper-bound of the substring.
An improvement here could be to add another if function that checks the character length within the Long press and performs a clear if there is only one character remaining.
I have around 5 edittexts.When i click submit button,it has to check whether all fields are entered or not.Along with it if any value is not entered,the focus has to go to that desired edittext.If there are many editexts empty,then the focus has to go in top down order.I have used seterror method but when i type in that editext the error msg is not going.After entering values the focus is not going to the next edittext.how to solve this issue?
caseno,dateloss,policy_rep,reg_book,Dri_lic are the different editexts used.I have written code for one editext below
caseno.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasfocus)
{
if(!hasfocus && caseno.getText().length()==0)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run() {
//ev2.clearFocus();
dateloss.clearFocus();
policy_rep.clearFocus();
reg_book.clearFocus();
Dri_lic.clearFocus();
caseno.requestFocus();
caseno.setError("Enter this field");
}
}, 100);
}
}
});
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(caseno!=null||dateloss!=null||policy_rep!=null||reg_book!=null||Dri_lic!=null)
{
Send_reportclaim_Async reportsync=new Send_reportclaim_Async();
reportsync.execute();
}
}
});
Android provides a setError() method for this:
if(edttxtDescription.getText().toString().trim().equals(""))
{
edttxtDescription.setError("Please provide description");
}
Define a method to check whether your EditTexts have valid data:
private boolean validateEditTexts()
{
boolean valid = true;
if(edttxtDescription.getText().toString().trim().equals(""))
{
edttxtDescription.setError("Please provide description");
valid = false;
}
// Similarly check all your EditTexts here and set the value of valid
......
......
return valid;
}
To validate all your EditTexts, call validateEditTexts() which will return true or false accordingly.
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(validateEditTexts()){
Send_reportclaim_Async reportsync=new Send_reportclaim_Async();
reportsync.execute();
}
}
});
Try this. This will work.
Check this:
for(EditText edit : editTextList){
if(TextUtils.isEmpty(edit.getText()){
// EditText is empty
}
}
Maintain array of EditText references: Like
EditText[] allEts = { caseno, dateloss, policy_rep, reg_book, Dri_lic };
Write the below code in onClick of submit button:
for (EditText editText : allEts) {
String text = editText.getText().toString();
if (text.length() == 0) {
editText.setError("enter this field");
editText.requestFocus();
break;
}
}
And, implement addTextChangedListener for all edittexts to clear the error after entering the text.
caseno.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Editable text = caseno.getText();
if (caseno.getError() != null && text != null
&& text.length() > 0) {
caseno.setError(null);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
Use this on your button click
if(!textView1.toString().isEmpty() && !textView2.toString().isEmpty() && ...)
{
............
}
1) create this method
public static boolean isNullOrEmpty(String input) {
return input == null || input.isEmpty();
}
2) send data to it for validation
boolean answer = isNullOrEmpty(editText.gettext().toString());
btnsubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(TextUtils.isEmpty(caseno.getText().toString()))
{
caseno.requestFocus();
Toast.makeText(getApplicationContext(),"Enter the required fields", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(dateloss.getText().toString()))
{
dateloss.requestFocus();
Toast.makeText(getApplicationContext(),"Enter the required fields", Toast.LENGTH_LONG).show();
return;
}
}
Currently this setup is working for me...Thnks those who answered
I generate multiple EditText in a for-loop and want to update a "score" when focus is lost from one of the EditTexts. I also wish to check that the input is valid and if not, empty the EditText and set focus back to it.
The following code adds EditTexts and a onFocusChangeListener.
The problem is that when a score is not valid (updateScore(id) returns false), I want to empty the EditText and set the focus back to this view.
The problem in my code is that if I enter a value in EditText A that are not valid, and then click in EditText B. Both A and B have focus... I only want A to have focus...
How can I set the focus back to the previous EditText and be ready for new inputs to this view?
for (int player = 0; player < numPlayers; player++)
{
EditText valueET = new EditText(this);
valueET.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
Log.v("Focus", "Lagrer unna den som har blitt klikket, " + String.valueOf(v.getId()));
etHasFocus = (EditText) v;
}
});
valueET.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
if(!updateScore(v.getId()))
{
if (etHasFocus != null && v.getId() != etHasFocus.getId())
etHasFocus.clearFocus();
v.requestFocus();
}
});
valueET.setId(200+player*100+row);
valueET.setInputType(InputType.TYPE_CLASS_NUMBER);
valueET.setTextColor(Color.BLACK);
valueET.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tr.addView(valueET);
}
tl.addView(tr, new TableLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
The code for updateScore(id) is (simplified):
boolean updateScore(int id)
{
EditText t = (EditText) findViewById(id);
String text = t.getText().toString();
if( !text.equals(""))
{
int score = Integer.parseInt(text);
}
if(score != 9)
return false;
TextView total = (TextView) findViewById(ID_toal);
t2.setText(String.valueOf(score));
return true;
}
Code is updated, problem now is that onClick never is called... (So etHasFocus = null)
You can try keeping a track of which EditText has been clicked. For this, create a EditText variable:
EditText etHasFocus;
In addition to adding OnFocusChangeListener, add an OnClickListener as well:
valueET.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
etHasFocus = (EditText) v;
}
});
Now, inside your OnFocusChangeListener, make the following changes:
valueET.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus) {
if(!updateScore(v.getId())) {
// Clear focus from another EditText
if (etHasFocus != null && v.getId() != etHasFocus.getId()) {
etHasFocus.clearFocus();
}
v.requestFocus();
}
}
}
});
Edit:
You are right. the onClick(View) method is called on second click. I can suggest you an alternate approach. I have tried it and its working fine:
Create a EditText variable:
EditText etCurrent;
Set an OnTouchlistener on each EditText:
valueET.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (etCurrent != null) {
if (etCurrent.getId() != v.getId()) {
if (!check(etCurrent.getId())) {
etCurrent.setSelection(0,
etCurrent.getText().toString().length());
return true;
} else {
etCurrent = (EditText) v;
}
}
} else {
etCurrent = (EditText) v;
}
}
return false;
}
});
Remove OnClickListener, onFocusChangeListener and etHasFocus.
You don't need to initialize etCurrent as if (etCurrent != null) { } else { } takes care of that.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have 5 EditTexts in android. I would like to know if I could check if all 5 EditTexts are null. Is there any way to do this??
I did something like this once;
EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
return;
}
private boolean isEmpty(EditText etText) {
if (etText.getText().toString().trim().length() > 0)
return false;
return true;
}
OR As Per audrius
private boolean isEmpty(EditText etText) {
return etText.getText().toString().trim().length() == 0;
}
If function return false means edittext is not empty and return true means edittext is empty...
For validating EditText use EditText#setError method for show error and for checking empty or null value use inbuilt android class TextUtils.isEmpty(strVar) which return true if strVar is null or zero length
EditText etUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = etUserName.getText().toString();
if(TextUtils.isEmpty(strUserName)) {
etUserName.setError("Your message");
return;
}
try this :
EditText txtUserName = (EditText) findViewById(R.id.txtUsername);
String strUserName = usernameEditText.getText().toString();
if (strUserName.trim().equals("")) {
Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
return;
}
or use the TextUtils class like this :
if(TextUtils.isEmpty(strUserName)) {
Toast.makeText(this, "plz enter your name ", Toast.LENGTH_SHORT).show();
return;
}
Way late to the party here, but I just have to add Android's own TextUtils.isEmpty(CharSequence str)
Returns true if the string is null or 0-length
So if you put your five EditTexts in a list, the full code would be:
for(EditText edit : editTextList){
if(TextUtils.isEmpty(edit.getText()){
// EditText was empty
// Do something fancy
}
}
Other answers are correct but do it in a short way like
if(editText.getText().toString().isEmpty()) {
// editText is empty
} else {
// editText is not empty
}
Try this
TextUtils.isEmpty(editText.getText());
You can use length() from EditText.
public boolean isEditTextEmpty(EditText mInput){
return mInput.length() == 0;
}
I usually do what SBJ proposes, but the other way around. I simply find it easier to understand my code by checking for positive results instead of double negatives.
You might be asking for how to check for empty EdiTexts, but what you really want to know is if it has any content and not that it is not empty.
Like so:
private boolean hasContent(EditText et) {
// Always assume false until proven otherwise
boolean bHasContent = false;
if (et.getText().toString().trim().length() > 0) {
// Got content
bHasContent = true;
}
return bHasContent;
}
As SBJ I prefer to return "has no content" (or false) as default to avoid exceptions because I borked my content-check. That way you will be absolutely certain that a true has been "approved" by your checks.
I also think the if calling it looks a bit cleaner as well:
if (hasContent(myEditText)) {
// Act upon content
} else {
// Got no content!
}
It is very much dependent on preference, but i find this easier to read. :)
Why not just disable the button if EditText is empty? IMHO This looks more professional:
final EditText txtFrecuencia = (EditText) findViewById(R.id.txtFrecuencia);
final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleStartStop);
txtFrecuencia.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
toggle.setEnabled(txtFrecuencia.length() > 0);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
I use this method, that uses trim() to avoid blank spaces :
EditText myEditText = (EditText) findViewById(R.id.editUsername);
if ("".equals(myEditText.getText().toString().trim()) {
Toast.makeText(this, "You did not enter a value!", Toast.LENGTH_LONG).show();
return;
}
an example if you have several EditText´s
if (("".equals(edtUser.getText().toString().trim()) || "".equals(edtPassword.getText().toString().trim()))){
Toast.makeText(this, "a value is missing!", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(textA.getText())){
showToast(it's Null");
}
you can use TextUtils.isEmpty like my Example !
Good luck
with this short code you can delete empty space at start and end of the string. If the string is "" return the message "error" else you ave a string
EditText user = findViewById(R.id.user);
userString = user.getText().toString().trim();
if (userString.matches("")) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
return;
}else{
Toast.makeText(this, "Ok", Toast.LENGTH_SHORT).show();
}
private boolean hasContent(EditText et) {
return (et.getText().toString().trim().length() > 0);
}
I used TextUtils for this:
if (TextUtils.isEmpty(UsernameInfo.getText())) {
validationError = true;
validationErrorMessage.append(getResources().getString(R.string.error_blank_username));
}
You can also check all the EditText Strings in one If condition: like this
if (mString.matches("") || fString.matches("") || gender==null || docString.matches("") || dString.matches("")) {
Toast.makeText(WriteActivity.this,"Data Incomplete", Toast.LENGTH_SHORT).show();
}
I wanted to do something similar. But getting the text value from edit text and comparing it like (str=="") wasn't working for me. So better option was:
EditText eText = (EditText) findViewById(R.id.etext);
if (etext.getText().length() == 0)
{//do what you want }
Worked like a charm.
Try this out with using If ELSE If conditions. You can validate your editText fields easily.
if(TextUtils.isEmpty(username)) {
userNameView.setError("User Name Is Essential");
return;
} else if(TextUtils.isEmpty(phone)) {
phoneView.setError("Please Enter Your Phone Number");
return;
}
You could call this function for each of the edit texts:
public boolean isEmpty(EditText editText) {
boolean isEmptyResult = false;
if (editText.getText().length() == 0) {
isEmptyResult = true;
}
return isEmptyResult;
}
EditText txtUserID = (EditText) findViewById(R.id.txtUserID);
String UserID = txtUserID.getText().toString();
if (UserID.equals(""))
{
Log.d("value","null");
}
You will see the message in LogCat....
"check out this i m sure you will like it."
log_in.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
username=user_name.getText().toString();
password=pass_word.getText().toString();
if(username.equals(""))
{
user_name.setError("Enter username");
}
else if(password.equals(""))
{
pass_word.setError("Enter your password");
}
else
{
Intent intent=new Intent(MainActivity.this,Scan_QRActivity.class);
startActivity(intent);
}
}
});
use TextUtils.isEmpty("Text here"); for single line code
The following works for me all in one statement:
if(searchText.getText().toString().equals(""))
Log.d("MY_LOG", "Empty");
First I retrieve a text from the EditText and then convert it to a string and finally comparing it with "" using .equals method.
This function work for me
private void checkForm() {
EditText[] allFields = {
field1_txt,
field2_txt,
field3_txt,
field4_txt
};
List < EditText > ErrorFields = new ArrayList < EditText > ();
for (EditText edit: allFields) {
if (TextUtils.isEmpty(edit.getText())) {
// EditText was empty
ErrorFields.add(edit); //add empty Edittext only in this ArayList
for (int i = 0; i < ErrorFields.size(); i++) {
EditText currentField = ErrorFields.get(i);
currentField.setError("this field required");
currentField.requestFocus();
}
}
}
}
EditText edt=(EditText)findViewById(R.id.Edt);
String data=edt.getText().toString();
if(data=="" || data==null){
Log.e("edit text is null?","yes");
}
else {
Log.e("edit text is null?","no");
}
do like this for all five edit text
You can use setOnFocusChangeListener , it will check when focus change
txt_membername.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean arg1) {
if (arg1) {
//do something
} else {
if (txt_membername.getText().toString().length() == 0) {
txt_membername
.setError("Member name is not empty, Plz!");
}
}
}
});
if ( (usernameEditText.getText()+"").equals("") ) {
// Really just another way
}
I prefer using ButterKnife list binding and then applying actions on the list. For example, with the case of EditTexts, I have the following custom actions defined in a utility class (in this case ButterKnifeActions)
public static <V extends View> boolean checkAll(List<V> views, ButterKnifeActions.Check<V> checker) {
boolean hasProperty = true;
for (int i = 0; i < views.size(); i++) {
hasProperty = checker.checkViewProperty(views.get(i), i) && hasProperty;
}
return hasProperty;
}
public static <V extends View> boolean checkAny(List<V> views, ButterKnifeActions.Check<V> checker) {
boolean hasProperty = false;
for (int i = 0; i < views.size(); i++) {
hasProperty = checker.checkViewProperty(views.get(i), i) || hasProperty;
}
return hasProperty;
}
public interface Check<V extends View> {
boolean checkViewProperty(V view, int index);
}
public static final ButterKnifeActions.Check<EditText> EMPTY = new Check<EditText>() {
#Override
public boolean checkViewProperty(EditText view, int index) {
return TextUtils.isEmpty(view.getText());
}
};
And in the view code, I bind the EditTexts to a list and apply the actions when I need to check the views.
#Bind({R.id.edit1, R.id.edit2, R.id.edit3, R.id.edit4, R.id.edit5}) List<EditView> edits;
...
if (ButterKnifeActions.checkAny(edits, ButterKnifeActions.EMPTY)) {
Toast.makeText(getContext(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
}
And of course this pattern is extendable to checking any property on any number of views. The only downside, if you can call it that, is the redundancy of views. Meaning, to use those EditTexts, you would have to bind them to single variables as well so that you can reference them by name or you would have to reference them by position in the list (edits.get(0), etc.). Personally, I just bind each of them twice, once to a single variable and once to a the list and use whichever is appropriate.
To editText is empty try another this simple way :
String star = editText.getText().toString();
if (star.equalsIgnoreCase("")) {
Toast.makeText(getApplicationContext(), "Please Set start no", Toast.LENGTH_LONG).show();
}
Try this out:
its in Kotlin
//button from xml
button.setOnClickListener{
val new=addText.text.toString()//addText is an EditText
if(new=isNotEmpty())
{
//do something
}
else{
new.setError("Enter some msg")
//or
Toast.makeText(applicationContext, "Enter some message ", Toast.LENGTH_SHORT).show()
}
}
Thank you