Issue
I'm writing an Android app with minSdkVersion = 15 (testing on 19). I would like to have an overlay with a small phone picture in the middle. I added the drawable (xml) resource ic_smartphone_black_24dp from the standard Android's pictures and created an ImageView for the overlay like this:
<ImageView
android:id="@+id/overlay"
android:layout_width="0dp"
android:layout_height="0dp"
android:alpha="1."
android:background="@drawable/overlay_full"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
This renders the overlay, but the smartphone picture is stretched to the whole ImageView: 
I tried to scale the phone's picture in various ways (reading this, that and many others), but none of it worked. In particular I tried:
- adding
vectorDrawables.useSupportLibrary = trueto gradle.build - adding
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
to the Activity
- changing the
ImageViewtoandroid.support.v7.widget.AppCompatImageView(and setting the background in java code and not in xml) - passing
wrap_contentinstead of0dpaslayout_width/height(and removing the constraints) - setting the size in the
overlay_full:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/overlay_background">
<size
android:width="152dp"
android:height="152dp"/>
</item>
<item android:drawable="@drawable/ic_smartphone_black_24dp"
android:left="30dp"
android:top="30dp"
android:right="30dp"
android:bottom="30dp"
android:gravity="center"
android:scaleType="center"
android:width="30dp"
android:height="30dp">
<size
android:width="30dp"
android:height="30dp"/>
</item>
</layer-list>
The code works as expected in API 28 where I also tested. Any idea how to do this scaling in earlier API versions?
Solution
You could try something like this:
<ImageView
android:id="@+id/overlay"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="center"
android:background="@drawable/just_the_background"
app:srcCompat="@drawable/ic_smartphone_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
Also, you don't need to use AppCompat views directly in layouts, just let the library handle this for you (they are replaced automatically at build time). You only need to use them if you're extending them to add custom functionality.
Answered By - Philio
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.