Change Button Text and Action - Android Development

Change button text and action - android development

You can use setTag. So, your code will look like,

final Button testButton = (Button) findViewById(R.id.button1);
testButton.setTag(1);
testButton.setText("Play");
testButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick (View v) {
final int status =(Integer) v.getTag();
if(status == 1) {
mPlayer.start();
testButton.setText("Pause");
v.setTag(0); //pause
} else {
testButton.setText("Play");
v.setTag(1); //pause
}
}
});

About setTag

Change button text in code for Android app

// Clean the code then

Button button = (Button)findViewById(R.id.button);

Android studio, change button text with each click in java

Just simply do

 button.setText(set? "Hi" : "Hi again");

Android Programming - Changing Button Text Programmatically with Alert Dialog

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.

The Text doesn't change in Real Time

Your XML has already configured the test1 method to essentially act as an OnClickListener.onClick() method for that button, so just change that method to something like this:

public void test1(View v)
{
Toast.makeText(getApplicationContext(), "Test 1", Toast.LENGTH_LONG).show();

((Button)v).setText("test");
}

CHANGING the text of a button with SHARED PREFERENCES android studio

I guess here is what you want:

In your app, you have an EditText that allows users to input pokemon name. When users click on the toggle catch button,

  • If the pokemon name is captured (the pokemon name has been saved in the SharePreferences), then remove the pokemon name from the SharePreferences and set the text of the button to "Release".

  • If the pokemon name is not captured (the pokemon name hasn't been saved in the SharePreferences), then add the pokemon name to the SharePreferences and set the text of the button to "Catch!".

Solution

public void toggleCatch(View view) {
String name = nameTextView.getText().toString().trim();
SharedPreferences captured = getSharedPreferences("pokemon_name", Context.MODE_PRIVATE);
boolean caught = captured.contains(name);
if (caught) {
captured.edit().remove(name).apply();
catch_button.setText("Release");
} else {
captured.edit().putBoolean(name, true).apply();
catch_button.setText("Catch!");
}
}


Related Topics



Leave a reply



Submit