[英]How to dynamically set drawable resource to ImageView?
我使用函數drawCircle(int diameter)
返回ShapeDrawable
對象,它是一個OvalShape。 然后,我使用ImageView.setImageDrawable()
設置OvalShape。 但是ImageViews
仍然為空。 如何正確做?
函數drawCircle()
:
public ShapeDrawable drawCircle (int diameter) {
OvalShape ovalShape = new OvalShape();
ShapeDrawable drawable = new ShapeDrawable(ovalShape);
drawable.getPaint().setColor(getResources().getColor(R.color.textColorHint));
drawable.getPaint().setStyle(Paint.Style.FILL_AND_STROKE);
drawable.getPaint().setStrokeWidth((float)2);
drawable.setBounds(0 ,0, diameter, diameter);
return drawable;
}
設置ImageView
:
one_img.setImageDrawable(drawCircle(selector_one_diameter));
two_img.setImageDrawable(drawCircle(selector_two_diameter));
最重要的是,我嘗試使用.xml
文件描述橢圓形。 但是由於dimens.xml
值無法用Java代碼重寫,因此我無法動態更改橢圓形的大小。 如果您可以提出其他建議,那就再好不過了!
這可能是由於您尚未設置繪制對象的高度,高度。 您可以使用以下代碼設置默認大小。
drawable.setIntrinsicWidth();
drawable.setIntrinsicHeight();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.