Friday, January 9, 2015

How to change Button font programmatically in Android

MainActivity.java code snippet

//require to import View class
public void perform_action(View v)
{
 //require to import Button class
 Button btn2 = (Button) findViewById(R.id.push_button2);
 //require to import Typeface class
 btn2.setTypeface(Typeface.MONOSPACE);
 btn2.setText("Button Typeface - Monospace");

 Button btn3 = (Button) findViewById(R.id.push_button3);
 btn3.setTypeface(Typeface.SERIF);
 //set the button new text
 btn3.setText("Button Typeface - Serif");

 Button btn4 = (Button) findViewById(R.id.push_button4);
 //set the button new typeface (font)
 btn4.setTypeface(Typeface.SANS_SERIF);
 btn4.setText("Button Typeface - SANS_SERIF");
}
Imported Class

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