简体   繁体   English

在AndroidTestCase中设置视图的宽度和高度

[英]Setting Width and Height of a View in AndroidTestCase

I am having some issues with View dimensions when writing test cases for an Android Library project. 在为Android库项目编写测试用例时,View尺寸存在一些问题。 Specifically, I am using AndroidTestCase to test a custom View class which (among other things) can generate bitmaps of its contents. 具体来说,我正在使用AndroidTestCase测试自定义View类,该类可以(除其他外)生成其内容的位图。 When creating the bitmaps, the class sets the width and height of the bitmap based on its own width and height: 创建位图时,该类根据其自身的宽度和高度设置位图的宽度和高度:

public Bitmap getBitmap(){
  Bitmap output = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888);
  //Fill in the Bitmap
  return output;
}

Some sample code for what I'm trying to do: 一些我想做的示例代码:

public void testBitmap(){
  LinearLayout l = new LinearLayout(getContext());
  MyCustomView myView = new MyCustomView(getContext());
  l.addView(myView);
  //draw things in myView
  Bitmap b = myView.getBitmap();
}

This works within an application if I'm inflating the parent l from an xml layout, but when I create all the views programmatically within a unit test, myView.getWidth() and myView.getHeight() both return 0. This results in an error: 如果我要从xml布局中放大父级l,则此方法在应用程序中有效,但是当我在单元测试中以编程方式创建所有视图时,myView.getWidth()和myView.getHeight()均返回0。错误:

java.lang.IllegalArgumentException: width and height must be > 0
at android.graphics.Bitmap.createBitmap(Bitmap.java:687)

Based on some other posts, I tried adjusting the width and height of myView using LayoutParams: 根据其他一些文章,我尝试使用LayoutParams调整myView的宽度和高度:

myView.setLayoutParams(new LinearLayout.LayoutParams(100, 100));

I also tried setting the LayoutParams of the parent layout, l, in a similar manner. 我也尝试以类似的方式设置父布局l的LayoutParams。 However, neither of these succeeded in changing the width and height of myView; 但是,这些方法都没有成功更改myView的宽度和高度; getWidth() and getHeight() still return 0. Is there some way I can ensure that the width and height of myView are non-zero? getWidth()和getHeight()仍返回0。是否可以通过某种方式确保myView的宽度和高度不为零?

Any help is greatly appreciated. 任何帮助是极大的赞赏。

Found my own answer. 找到了我自己的答案。

After trying a few things, I found that instead of: 尝试了几件事之后,我发现它不是:

myView.setLayoutParams(new LinearLayout.LayoutParams(100, 100));

I could use: 我可以使用:

myView.layout(0, 0, 100, 100);

So the whole sample code would look like this: 因此,整个示例代码如下所示:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM