如何保持imageView不在屏幕上[Kotlin]

深红空间:

所以我是Kotlin的新手,我正在尝试制作一个超级简单的应用程序。它所做的就是当我单击“向右”按钮时它与向左按钮一样向右移动。问题是当我单击任一按钮(例如,右键)时,我可以单击它,直到图像完全脱离屏幕为止。那么,如何实现一个代码,一旦它到达屏幕边缘,它就会停止移动?

我的密码

package com.example.change_position_circle

import android.animation.ObjectAnimator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //val picture = findViewById<ImageView>(R.id.SpongeBob)
        val right_button = findViewById<Button>(R.id.right)
        val left_button = findViewById<Button>(R.id.left)


        right_button.setOnClickListener()
        {
            //ObjectAnimator.ofFloat(SpongeBob, "x", 100)

            SpongeBob.animate().setDuration(90).translationXBy(100f)
        }

        left_button.setOnClickListener()
        {
            //ObjectAnimator.ofFloat(SpongeBob, "translationXBy", 100f).apply {
            //duration = 200
            // start()
            SpongeBob.animate().setDuration(90).translationXBy(-100f)
            //}
        }
    }
}

我可以一直单击直到完全脱离屏幕

谢谢您的帮助

仙人掌

欢迎来到科特林!

So yeah, you've got your Spongebob animating, now you need some logic to control that animation. The problem here is you don't always want that full animation to happen, right? If he's too close to the edge of the screen, you want the button to only move him as far as that invisible wall (and if he's right against it, that means no movement at all).

The animation and drawing systems don't put any restrictions on where you can put a View, so it's up to you to handle that yourself. You basically need to do this when a button is clicked:

  • get the Spongebob's position coordinates (it's the X you really care about right now)
  • work out the position of the edge you care about (the View's coordinates describe where the top left corner is, so if you're looking at the right edge, you need that X coordinate + the width of the View)
  • work out the X coordinate of the edge of the screen (or parent layout, whatever you want the Spongebob to be contained within)
  • if the distance between the Spongebob edge and the screen edge is less than your normal animation movement, you need to change it to that remaining distance
  • you'll also want to work out the appropriate duration too, if he's moving half the usual distance the animation should take half as long

that's a lot to work on, and there are a few ways to do it, but here's one approach just using the screen edges as the bounds

    import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import kotlin.math.abs
import kotlin.math.min

private const val MOVE_DISTANCE = 100
private const val MOVE_TIME = 90

class MainActivity : AppCompatActivity() {
    private var screenWidth = 0
    private lateinit var spongeBob : View

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.spongebob)

        // store this when the Activity is created, if the device is rotated the Activity
        // will be recreated and this method gets run again
        screenWidth = applicationContext.resources.displayMetrics.widthPixels

        //val picture = findViewById<ImageView>(R.id.SpongeBob)
        val right_button = findViewById<Button>(R.id.right)
        val left_button = findViewById<Button>(R.id.left)
        spongeBob = findViewById(R.id.spongeBob)

        right_button.setOnClickListener()
        {
            // two possible values - the distance to the edge, and the normal amount we move
            // we want the smaller of the two (i.e. always move the normal amount, unless
            // the edge is closer than that
            val distance = min(distanceToEdge(left = false), MOVE_DISTANCE)
            moveSpongeBob(distance)
        }

        left_button.setOnClickListener()
        {
            val distance = min(distanceToEdge(left = true), MOVE_DISTANCE)
            // we're moving left so we need to use a negative distance
            moveSpongeBob (-distance)
        }
    }

    private fun distanceToEdge(left: Boolean): Int {
        // Get the Spongebob's top-left position - the call is a method on the View class,
        // I'm assuming SpongeBob is a View, and you need to pass an array in because
        // that's just how it works for whatever reason...
        val location = IntArray(2)
        spongeBob.getLocationOnScreen(location)
        val x = location[0]

        // I'm just using the View.getWidth() call here (Kotlin style) but I don't know
        // what the SpongeBob class is, so you'll need to handle this
        // You could set this once, like when we get the screen width, but width will be 0 until
        // the View is laid out - so you can't do it in #onCreate, #onViewCreated should work
        val spongeBobWidth = spongeBob.width

        // the left edge is just the x position, however far that is from zero
        return if (left) x
        // the right edge is the x position plus the width of the bob
        else screenWidth - (x + spongeBobWidth)
    }

    // Actually move the view, by the given distance (negative values to move left)
    private fun moveSpongeBob(distance: Int) {
        // work out how much this distance relates to our standard move amount, so we can
        // adjust the time by the same proportion - converting to float so we don't get
        // integer division (where it's rounded to a whole number)
        val fraction = distance.toFloat() / MOVE_DISTANCE
        // distance can be negative (i.e. moving left) so we need to use the abs function
        // to make the duration a postitive number
        val duration = abs(MOVE_TIME * fraction).toLong()
        spongeBob.animate().setDuration(duration).translationXBy(distance.toFloat())
    }
}

您可以做的更好的事情(SpongeBob应该称为spongeBob并且是View),但这是基础。关于坐标系的这篇文章也可能对您有所帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章