6

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?

Amandeep Grewal
  • 1,801
  • 3
  • 19
  • 30

3 Answers3

1

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);
Noah
  • 15,080
  • 13
  • 104
  • 148
0

The only solution that worked for me: Resize Text to Fit the View in Android [source code]

In short, override the onDraw method to suit your needs.

Vanuan
  • 31,770
  • 10
  • 98
  • 102
0

you can get the screen resolution , and in your code, you can adapt the size of the text of your buttons by changing the LinearLayout.LayoutParams

EDIT : algorithm

First : get the screen resolutions, to see if your phone is a small,meduim or big .(to do this , use the class : DisplayMetrics )

Second : in your code , you will test for every type of size ( in general i think 3 : small , meduim,big ) , and modify the textSize of your buttons like this :

btn.setTextSize(float size ) ; 
Houcine
  • 24,001
  • 13
  • 56
  • 83