Disable a button after is has been clicked, android - android

I am trying to disable the button after it is clicked. Th app doesn't crash it just doesn't disable it. wondering could anyone help me out?
here is the on click method for the button i am trying to disable.
//Submit button for answer
final Button submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
EditText answerA = (EditText) findViewById(R.id.answerA);
String toCompare = answerA.getText().toString();
TextView score = (TextView)findViewById(R.id.score_text_a);
scoreKeeper scoremgr = new scoreKeeper();
//anaswer to input
if(toCompare.matches("Alligator") || toCompare.matches("alligator") ||
(toCompare.matches("Alligator ") || toCompare.matches("alligator "))) {
//adds to score if inout matches one of the above
scoremgr.addToScore();
score.setText("Your score is " +Integer.toString(scoremgr.checkScore()));
//calls the next letter class
Intent intent_b = new Intent(button_a.this, button_b.class);
startActivity(intent_b);
//displays a toast message if correct
Toast.makeText(button_a.this, "Well Done, You Got it Right", Toast.LENGTH_SHORT).show();
submit.setEnabled(false);
}else{
//displays a toast meaasge if wrong
Toast.makeText(button_a.this, "Wrong Answer, Try Again", Toast.LENGTH_SHORT).show();
}
}
});

You put your "setEnabled" under an if statement. Just put it before. If that's a feature, check if the correct statement is executed, the condition is probably invalid, resulting the button not being disabled.

In first place, check if your code are being executed, you are doing it right, also you can try to use to disable your button:
btn.setEnabled(false);
btn.setClickable(false);
Also, change your Button variable to an instance variable without final
and access it inside your onClick method.
If you want to remove the button from your layout, you can change the visibility on it:
btn.setVisibility(View.GONE):

in your xml file set
android:clickable="true"
and now
btn.setEnabled(false);
btn.setClickable(false);
and check your (if condition ) does it returns true or not

Related

checking for empty values in textfield and spinner

Button btnSearch = (Button) pnlView.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new OnClickListener() {#
Override
public void onClick(View v) {
results.clear();
if (txtPatientID.getText().equals("") && txtFirstName.getText().equals("")
&& txtLastName.getText().equals("") && txtDOB.getText().equals("")
&& cboGender.getSelectedItem().equals("")) {
Toast.makeText(getActivity(),
"No criteria added", Toast.LENGTH_LONG).show();
return;
}
new Async().execute();
}
});
I have four text field and a spinner, when the user clicks search button, i need to display a message saying no criteria added. Its working, but i am not sure whether i am following the right approach in checking for empty value in textfield and spinner.
You should check the length instead of comparing with empty value. Because it will fail in one or more cases. you should check like this
if(txtPatientID.getText().toString().trim().length()==0)
trim() method will remove one or more spaces in your text
This seems okay. But you can trim() the getText() results to handle empty space characters.

Modifiy text in a button - if statement

I am currently creating an android application with different options. One of the option would be to have a button that would show "Activate" as default. When the application would be running, clicking on it would change it to "Disable" and then to "activate" if clicked again. I believe that all I have to do is to .getText with a string variable then use this variable in a if statement but it seems like it is not reacting to any of my conditions...
final Button button = (Button) findViewById(R.id.bSensor);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
String buttonText = button.getText().toString();
if (buttonText == "#string/Disable") {
button.setText(R.string.Enable);
}
else if (buttonText == "#string/Enable"){
button.setText(R.string.Disable);
}
}
});
Thanks for help
Phyzikk
You shouldn't use the == operator when comparing strings in Java. Source
You should either use the .equals() method of the string, or alternatively you could keep a global boolean state flag to determine which value is set. This way you won't need to do a string compare every time you need to figure out if it's active or disabled.
Use .equals to compare strings. You wont need the #String/ prefix as this is not part of what the button displays.
final Button button = (Button) findViewById(R.id.bSensor);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
String buttonText = button.getText().toString();
if (buttonText.equals(getResources().getText(R.string.Disable)) {
button.setText(R.string.Enable);
}
else if (buttonText.equals(getResources().getText(R.string.Enable)){
button.setText(R.string.Disable);
}
}
});

Delete last character of edittext

I have a quick question.
I have a screen with some numbers, when you click one of the numbers, the number gets appended to the end of the edittext.
input.append(number);
I also have a backbutton, when the user clicks this button I want to remove the last character.
At the moment I have the following :
Editable currentText = input.getText();
if (currentText.length() > 0) {
currentText.delete(currentText.length() - 1,
currentText.length());
input.setText(currentText);
}
Is there an easier way to do this ? Something in the line of input.remove()?
I realise this is an old question but it's still valid. If you trim the text yourself, the cursor will be reset to the start when you setText(). So instead (as mentioned by njzk2), send a fake delete key event and let the platform handle it for you...
//get a reference to both your backButton and editText field
EditText editText = (EditText) layout.findViewById(R.id.text);
ImageButton backButton = (ImageButton) layout.findViewById(R.id.back_button);
//then get a BaseInputConnection associated with the editText field
BaseInputConnection textFieldInputConnection = new BaseInputConnection(editText, true);
//then in the onClick listener for the backButton, send the fake delete key
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textFieldInputConnection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
}
});
try this out,
String str = yourEditText.getText().toString().trim();
if(str.length()!=0){
str = str.substring( 0, str.length() - 1 );
yourEditText.setText ( str );
}

How do I make a button execute code only if text is entered in a field?

I'm making an app for Android, and if you click the calculate button on one of the pages, without anything entered in the text boxes, it force closes. Some users were wondering if this could be fixed, so I was wondering if there was a way to make the onClickListener execute only if there is something inside the EditText.
You have to check it yourseft, such as:
final EditText editText = ...; // your edit
// check in your onClickListener
if (editText.getText().toString().isEmpty){ // Check if your EditText is
}else{ // If your EditTexit is not null
}
Please, search google before asking any question!
You can try following code,
suppose you have a EditText txtNum1 & txtNum2 , so onClickListener() method you can write following condition
public void onClick(View v)
{
if ( v == cmdCalculate )
{
if ( !txtNum1.getText().equals("") && !txtNum2.getText().equals("") )
{
// your calculation code
}
else
{
// post error msg code
}
}
}

how to take input from user in android

i have a EditText in android in which i want the user to enter the text and checks for the condition "BYE"
Code sample:
EditText text = (EditText)findViewById(R.id.EditText01);
String abc= text .getText().toString();
while( !(abc).equals("bye")){
abc = text.getText().toString();//user should enter the text from keyboard and the while loop should go and chech the condition.but not able to enter the text
//do some operation with abc
}
How can i make user to enter the text??The UI should wait for the text to be entered(something like we have InputStreamReader in java applications).
Very Simple:-
EditText text = (EditText)findViewById(R.id.EditText01);
String str = text.getText().toString();
now in str u will get string which is entered in EditText
I don't think you need a loop to do this. From your comment it looks like you also have an "Enter" button or something that you click to do the checking. Just set an onclicklistener and onclick you can make the edittext invisible (or un-editable), check is the edittext is equal to "BYE" and then do your actions might look something like this:
final EditText ET = (EditText) findViewById(R.id.EnterText);
Button B1 = (Button) findViewById(R.id.EnterButton);
B1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ET.setVisibility(View.INVISIBLE);
if(ET.getText().toString() == "BYE")
{
//do something if it is "BYE"
} else {
Context context = getApplicationContext();
CharSequence text = "Please enter BYE";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
ET.setVisibility(View.VISIBLE);
} });
Instead of running this check in an infinite loop, only run it on every onKeyUp of the EditText. You know, anyway, that the condition will only ever be fulfilled if the user actually enters something.

Categories

Resources