Friday, January 9, 2015

How to change Button text size programmatically in Android

MainActivity.java code snippet

//require to import View class
public void perform_action(View v)
{
 //require to import Button class
 Button btn1 = (Button) findViewById(R.id.push_button);
 //require to import TypedValue class
 //set the button text size 30dp
 btn1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
 btn1.setText("Button Text Size 30 DP (Device-Independent-Pixels)");

 Button btn2 = (Button) findViewById(R.id.push_button2);
 //set the button text size 0.30in
 btn2.setTextSize(TypedValue.COMPLEX_UNIT_IN, 0.30f);
 btn2.setText("Button Text Size 0.30in (Inches)");

 Button btn3 = (Button) findViewById(R.id.push_button3);
 //set the button text size mm
 btn3.setTextSize(TypedValue.COMPLEX_UNIT_MM, 7);
 btn3.setText("Button Text Size 7mm (Millimeters)");

 Button btn4 = (Button) findViewById(R.id.push_button4);
 //set the button text size 30pt
 btn4.setTextSize(TypedValue.COMPLEX_UNIT_PT, 30);
 btn4.setText("Button Text Size 30pt (Points)");

 Button btn5 = (Button) findViewById(R.id.push_button5);
 //set the button text size 55px
 btn5.setTextSize(TypedValue.COMPLEX_UNIT_PX, 55);
 btn5.setText("Button Text Size 55px (Pixels)");

 Button btn6 = (Button) findViewById(R.id.push_button6);
 //set the button text size 30sp
 btn6.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
 btn6.setText("Button Text Size 30sp (Scale-Independent-Pixels)");
}
Imported Class

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