TR15 TR15 - 4 months ago 33
Java Question

Android Programming - Changing Button Text Programmatically with Alert Dialog

I'm trying to create an app for editing guitar tabs. I have an array of buttons that represent the frets and I want to be able to click on the button to open an alert dialog to set the text of that button to be the number that's input.

The editFret function below is called by the button through its onClick property. When I run this, I can press on a button and it brings up the dialog and I can input the number fine. After pressing OK on the dialog though, the button just becomes blank. When I click on the button again, or any other button, the number then shows up as the text in the button. It also keeps changing the text in any buttons clicked afterwards to whatever the last input value was.

I tried changing the button text to a constant value on a click and didn't have any problems so I'm assuming the problem is with the getFret function although I can't possibly see what it would be as it's just fetching a string.

//Create string to store the fret number
String fret;

public void getFret(){
//Create text input field
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setFilters(new InputFilter[] {new InputFilter.LengthFilter(2)});

new AlertDialog.Builder(this)
.setTitle("Edit fret")
.setMessage("Input fret number")
.setView(input)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
fret = input.getText().toString();
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Do nothing
}
}).show();
}

public void editFret(View view){
Button button = (Button) view;
getFret();
button.setText(fret);
button.invalidate(); //Don't know if this is necessary
}

Answer

You need to change your setPositiveButton to:

.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    fret = input.getText().toString();
                    button.setText(fret);
                }
            })

and change Button to global variable instead of local one.

The problem here is when you are calling editFret(View view) it will also call getFret() that will show the dialog and then call button.setText(fret) without waiting for the user to press OK or Cancel so you need to set the text when the OnClickListener is called.