Question

I am having some issues with View dimensions when writing test cases for an Android Library project. Specifically, I am using AndroidTestCase to test a custom View class which (among other things) can generate bitmaps of its contents. 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:

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:

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

I also tried setting the LayoutParams of the parent layout, l, in a similar manner. However, neither of these succeeded in changing the width and height of myView; getWidth() and getHeight() still return 0. Is there some way I can ensure that the width and height of myView are non-zero?

Any help is greatly appreciated.

Was it helpful?

Solution

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top