Rgfvfk Iff
Rgfvfk Iff

Reputation: 1609

Programatically created drawable not shown in imageview

I am trying to create a rectangle drawable inside an image view.

val backgroundRect = GradientDrawable()
backgroundRect.shape = GradientDrawable.RECTANGLE
backgroundRect.setBounds(0,0, 100, 100)
backgroundRect.setStroke(5, Color.parseColor("#585858"))
backgroundRect.setColor(Color.parseColor("#FF9009"))

val image = ImageView(context)
image.layoutParams = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT)
image.setImageDrawable(backgroundRect)
rootView.addView(image)

The problem is if I set the ImageView layout params as WRAP_CONTENT then nothing displays but if I set the params as image.layoutParams = ConstraintLayout.LayoutParams(100, 100) then the ImageView is displayed. I tried creating the rectangle drawable using xml and if I set it there the image is still shown.

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/dummyRectangle"/>

Do I need to always specify the layout params variable or is there another way to set it?

Upvotes: 1

Views: 304

Answers (3)

Kaveri
Kaveri

Reputation: 1088

Size needs to be specified for atleat one imageview or be drawable .

For the gradient drawable it can be done as answered above and now the imageview wraps according to drawable size .

Otherwise in case imageview is given a size,as per the doc:-

The shape scales to the size of the container View proportionate to the dimensions defined here, by default. When you use the shape in an ImageView, you can restrict scaling by setting the android:scaleType to "center"

Alternative ways to achieve the similar(depends on use):

1.Drawing the drawable from xml. // define size for drawable in xml itself.

2.You can also draw your shape as its own custom view and add it to a layout in your app.

3.create some custom drawings, you can do so by extending the Drawable class, later set in to imageview

Upvotes: 0

Anisuzzaman Babla
Anisuzzaman Babla

Reputation: 7480

Just set a size to your GradientDrawable

backgroundRect.setSize(100,100);

Because your view has no size yet. And when you used wrap_content you did not have any content to wrap.

Upvotes: 1

Mahdi M
Mahdi M

Reputation: 57

You should set size for backgroundRect . The backgroundRect dosen't have any size and as you set it to wrap content it doens't shown.

Upvotes: 0

Related Questions