Saturday, January 10, 2015

How to set Button text programmatically in Android

activity_main.xml code snippet

<Button
 android:id ="@+id/push_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Click To Change Text"
 android:textSize="35sp"
 android:onClick="perform_action"
 />
MainActivity.java code snippet

public void perform_action(View v)
{
 Button btn = (Button) findViewById(R.id.push_button);
 //set button's new text programmatically
 //setText() method allow us to set a widget's displayed text
 btn.setText("Text changed by button click");
}
Imported Class

import android.view.View;
import android.widget.Button;
More android examples