I have an error in android studio 4.1.1 I want make image"student_bg" draggable so I added this code and it didn't worked.
this is my tutorial.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="horizontal">
<ImageView
android:id="@+id/character"
android:layout_width="35dp"
android:layout_height="100dp"
android:clickable="true"
app:srcCompat="@drawable/student_bg" />
</LinearLayout>
and this is my tutorial.kt
var moveX = 0f
var moveY = 0f
class tutorial : AppCompatActivity(), SensorEventListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
setContentView(R.layout.tutorial)
val st = findViewById<ImageView>(R.drawable.student_bg)
st.setOnTouchListener { v, event ->
when(event.action) {
MotionEvent.ACTION_DOWN -> {
moveX = v.x - event.rawX
moveY = v.y - event.rawY
}
MotionEvent.ACTION_MOVE -> {
v.animate()
.x(event.rawX + moveX)
.y(event.rawY + moveY)
.setDuration(0)
.start()
}
}
true
}
}
}
I found create ids.xml will help this issue, but it didn't worked. I made ids.xml
This is my .xml file: tutorial.xml
And this is my .kt file: turotial.kt
Did I missed something? Why it didn't work?
edit: this is my imports:
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.KeyEvent.*
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import java.util.Random
import kotlin.properties.Delegates
在tutorials.kt中,用“R.id.character”代替“R.drawable.student_bg”,因为findViewById需要一个id,但是你传递了一个drawable并删除了ids.xml
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.