![](/img/trans.png)
[英]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.