SVG image is not shown in dynamically added layout
See original GitHub issueHere is my simplest reproducible example: I have a linear layout cell.xml
which is dynamically inflated into a parent activity_main.xml
layout in the onCreate
method:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val linearLayout = findViewById<LinearLayout>(R.id.linearLayout)
val cell = layoutInflater.inflate(R.layout.cell, linearLayout, false)
val iv = cell.findViewById<ImageView>(R.id.image_cell)
iv.load("file:///android_asset/any.svg")
linearLayout.addView(cell)
}
My activity_main.xml
:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
My cell.xml
:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/image_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/image_cell"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:contentDescription="@+string/desc"
android:gravity="center"/>
</LinearLayout>
The svg displays correctly if I use attribute android:layout_height="wrap_content"
inside the image view, but it won’t display the svg image if android:layout_height="match_parent"
is used instead. For the record, I need the image_parent
linear layout to have android:layout_height="match_parent"
because the actual layouts of both xml’s contain some background drawables which eventually require the height attribute of image_parent
to be set to match_parent
.
I believe this problem applies to any svg, but if you cannot reproduce the issue please let me know, I will upload one svg file which I used.
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (3 by maintainers)
I agree that the issue stems from the 0 height measured when the image is loaded (changing
match_parent
inactivity_main.xml
does not work). My views are actually dynamically added,cell.xml
is just a cell of a table layout, whose cell widths are programmatically calculated. Currently I can solve this problem by (i) useandroid:layout_height=wrap_content
instead ofandroid:layout_height=match_parent
in the imageView, or (ii) force trigger the imageView to redraw by callinginvalidate()
inOnGlobalLayoutListener()
whenever the view bounds are newly calculated. The second solution is probably the safest way to go.@neoh-zz Circling back on this. I think this might be caused by your layout being measured as 0 height due to your
LinearLayout
being set toandroid:layout_height="wrap_content"
inactivity_main.xml
. Does it work if you change it tomatch_parent
? Optionally, you could setandroid:scaleType="centerCrop"
on yourImageView
.