LinearLayout mylinear = (LinearLayout)this.findViewById(R.id.mylinear);
Button btn = new Button(this);
mylinear.addView(btn);
代码如上,为什么当我使用setWidth()设置它的宽度时,如果设置为192以上就有效,设置为192以下就无效(宽度依然为192,无论我怎样设置宽度)
比如:
btn.setWidth(270); Log.("TAG",btn.getWidth()); 打印结果:270
btn.setWidth(200); Log.("TAG",btn.getWidth()); 打印结果:200
btn.setWidth(191); Log.("TAG",btn.getWidth()); 打印结果:192
btn.setWidth(180); Log.("TAG",btn.getWidth()); 打印结果:192
代码中无任何其它涉及到192这个值的地方,所以有疑问是不是代码设置button有限定一定的值
你的button里有使用什么东西吗?我刚刚去看了源码有下面几种情况会不用设置的width
width=(int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint));
width = Math.max(width, dr.mDrawableWidthTop);
width = Math.max(width, dr.mDrawableWidthBottom);
还有其他很多,一般这种width不是你设置多少就是多少,你设置的叫想,真正实现的时候还得看具体情况
找到解决方法了,如下:
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)btn.getLayoutParams();
lp.width = 50;
btn.setLayoutParams(lp);