Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximize size of Android button text

Tags:

android

button

I had multiple buttons in a LinearLayout horizontally. On a larger device all the button text fit on one line at 20sp text size. However, on a smaller device at 20sp text size, the text of the buttons goes to two lines.

How can I tell it to make the text size as big as possible so that text stays on one line?

like image 873
Amandeep Grewal Avatar asked May 27 '11 19:05

Amandeep Grewal


1 Answers

This works for me ... you will need to customize for your needs:

// Determine Scaled Density for later calculations
Display dd = ((Activity) m_Context).getWindowManager().getDefaultDisplay();
DisplayMetrics dm = new DisplayMetrics();
dd.getMetrics(dm);
float m_ScaledDensity = dm.scaledDensity;

Rect bounds = new Rect();
Paint p = new Paint();
p.setTypeface(btn.getTypeface());

// W is a very wide character
String sample = "NeedsToFIt"
int maxFont;
for (maxFont= 1
    ; -bounds.top <= btn.getHeight() && bounds.right <= btn.getWidth()
    ; maxFont++) {
  p.setTextSize(maxFont);
  p.getTextBounds(sample, 0, sample.length(), bounds);
}
maxFont = (int) ((maxFont - 1) / m_ScaledDensity);
btn.setTextSize(maxFont);
like image 161
Noah Avatar answered Oct 17 '22 12:10

Noah