【发布时间】:2014-05-16 09:10:58
【问题描述】:
在为 Android 库项目编写测试用例时,我遇到了一些视图维度问题。具体来说,我正在使用 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 的宽度和高度不为零?
非常感谢任何帮助。
【问题讨论】:
标签: java android android-testing