简体   繁体   中英

Move View to the center of another view, or alternatively to coordinates relative to screen size

I know this has been asked before but all the answers have used java, which I have absolutely no experience with. Also, android studio´s automatic translation to kotlin didn´t work on the code from those answers.

I´m creating a quiz game for which I want to have an animation. I have a view (a little pulsing dot) that I want to move to the center of the "correct" button and, upon hitting it, speed straight up and out of the screen. Now the last part is no problem, but I can´t think of a good way of moving the dot on the button. If I do it like in the example below, it won´t adapt to different screen sizes or even the screen orientation. So is there a way to set the coordinates as percentages/fractions of the screen? Or get the coordinates of the center of the button and move there?

So this is what I use so far:

        var soultoX = ObjectAnimator.ofFloat(mContentView, "x", 150f).apply {
        duration = 1000
    }
        var soultoY = ObjectAnimator.ofFloat(mContentView, "y", 1055f).apply {
        duration = 1000
    }

    fun soulToButton() = AnimatorSet().apply {
        play(soultoX).with(soultoY)
        start()
    }

The xml for one example button:

    <Button
        android:text="@string/fa"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fabutton"
        style="@style/Widget.AppCompat.Button.Colored"
        app:layout_constraintTop_toTopOf="@+id/guideline8" 
        app:layout_constraintBottom_toBottomOf="@+id/guideline7"
        android:textColorLink="@color/colorAccent" 
        android:textColor="@color/colorPrimary"
        app:layout_constraintVertical_bias="1.0"
        app:layout_constraintStart_toStartOf="@+id/guideline3"
        app:layout_constraintEnd_toStartOf="@+id/guideline4"/>

And the view:

    <Button
        android:text="@string/fa"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/fabutton"
        style="@style/Widget.AppCompat.Button.Colored"
        app:layout_constraintTop_toTopOf="@+id/guideline8" 
        app:layout_constraintBottom_toBottomOf="@+id/guideline7"
        android:textColorLink="@color/colorAccent"
        android:textColor="@color/colorPrimary"
        app:layout_constraintVertical_bias="1.0"
        app:layout_constraintStart_toStartOf="@+id/guideline3"
        app:layout_constraintEnd_toStartOf="@+id/guideline4"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM