I have 2 image views in Android. One is a wind turbine pole and the other one wind turbine blades. How can I set the layout constraints such that the wind turbine blades are always correctly attached to the pole? They should fit for different screen resolutions.
Here is the screenshot of the layout editor:
Here is the xml layout code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView_windTurbinePole"
android:layout_width="150dp"
android:layout_height="150dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/wind_turbine_pole" />
<ImageView
android:id="@+id/imageView_windTurbineBlade"
android:layout_width="120dp"
android:layout_height="120dp"
app:layout_constraintBottom_toTopOf="@+id/imageView_windTurbinePole"
app:layout_constraintEnd_toEndOf="@+id/imageView_windTurbinePole"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="@+id/imageView_windTurbinePole"
app:srcCompat="@drawable/wind_turbine_blade" />
</androidx.constraintlayout.widget.ConstraintLayout>
Update: The desired image should look like a "real" wind turbine where the blades are on the pole. The bigger picture is that I want to make an animation in Android in which the blades rotate.
If you need the view height to be a fraction of the screen height, you can use something like this:
app:layout_constraintHeight_percent="0.224"
Then, if you need to move the pole closer to the blades, you can do it in code in doOnPreDraw.
You can use it from Java, too:
androidx.core.view.ViewKt.doOnPreDraw(windTurbinePoleView, view -> {
windTurbinePoleView.setTranslationY(- FRACTION * windTurbineBlade.getHeight());
return null;
});
Here I'm moving windTurbinePoleView, you can apply a similar approach to windTurbineBladeView. FRACTION
is a constant that represents the distance between the blades' image bottom and the central circle bottom divided by the blades' image height.
If the 'doOnPreDraw' part isn't resolved, you can add the dependency androidx.core:core-ktx:VERSION
. Alternatively, you can use windTurbinePoleView.getViewTreeObserver().addOnPreDrawListener(...)
with the same purpose.