[英]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.