做项目时遇到一个问题,在定义button时没有在布局中定义,需要动态的生成很多button,但是有个问题就是button里的字体大小不好控制,因为事先不知道字体的多少,也就没法统一定义button的大小。后来在网上搜了搜,终于找到了解决方案,根据button的宽度动态的调整字体的大小,直接上代码:
public static void setTextInButton(final String text, final Button btn) {
OnGlobalLayoutListener ll = new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
btn.getViewTreeObserver().removeGlobalOnLayoutListener(this);//取消监听,很重要,要不然会很卡的
int width = btn.getWidth() - btn.getPaddingLeft() - btn.getPaddingRight();
int len = text.length();
btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float) (width / (len)) > 22 ? 22 : (float) (width / (len)));
}
};
btn.getViewTreeObserver().addOnGlobalLayoutListener(ll);
}具体的大小大家可以根据自己的情况再调整。
本文介绍了一种在Android开发中动态生成多个Button时,如何根据Button宽度自动调整字体大小的方法。通过监听全局布局变化,计算适合的文字大小,确保在不同长度文字的情况下保持良好的显示效果。
4997

被折叠的 条评论
为什么被折叠?



