[英]Dynamically setting height and width of a image view in android Fragment using LayoutParam
[英]Setting Width and Height of a View in AndroidTestCase
在为Android库项目编写测试用例时,View尺寸存在一些问题。 具体来说,我正在使用AndroidTestCase测试自定义View类,该类可以(除其他外)生成其内容的位图。 创建位图时,该类根据其自身的宽度和高度设置位图的宽度和高度:
public Bitmap getBitmap(){
Bitmap output = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888);
//Fill in the Bitmap
return output;
}
一些我想做的示例代码:
public void testBitmap(){
LinearLayout l = new LinearLayout(getContext());
MyCustomView myView = new MyCustomView(getContext());
l.addView(myView);
//draw things in myView
Bitmap b = myView.getBitmap();
}
如果我要从xml布局中放大父级l,则此方法在应用程序中有效,但是当我在单元测试中以编程方式创建所有视图时,myView.getWidth()和myView.getHeight()均返回0。错误:
java.lang.IllegalArgumentException: width and height must be > 0
at android.graphics.Bitmap.createBitmap(Bitmap.java:687)
根据其他一些文章,我尝试使用LayoutParams调整myView的宽度和高度:
myView.setLayoutParams(new LinearLayout.LayoutParams(100, 100));
我也尝试以类似的方式设置父布局l的LayoutParams。 但是,这些方法都没有成功更改myView的宽度和高度; getWidth()和getHeight()仍返回0。是否可以通过某种方式确保myView的宽度和高度不为零?
任何帮助是极大的赞赏。
找到了我自己的答案。
尝试了几件事之后,我发现它不是:
myView.setLayoutParams(new LinearLayout.LayoutParams(100, 100));
我可以使用:
myView.layout(0, 0, 100, 100);
因此,整个示例代码如下所示:
public void testBitmap(){
LinearLayout l = new LinearLayout(getContext());
l.layout(0, 0, 100, 100);
MyCustomView myView = new MyCustomView(getContext());
myView.layout(0, 0, 100, 100);
l.addView(myView);
//draw things in myView
myView.getBitmap();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.