【发布时间】:2019-09-27 07:49:03
【问题描述】:
我现在正在开发一个小应用程序来测试带有运动和触摸事件的 arround。我面临的问题是我的 Listener 类必须被抽象,但我无法从该侦听器创建一个对象,我需要将它放在 imageView 的“setOnTouchListener”方法上。
监听类:
abstract class GestureListener(directionDisplayer: TextView) : View.OnTouchListener,` GestureDetector.OnGestureListener {
private var directionDisplayer: TextView = directionDisplayer
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
val gestureDetector = GestureDetector(this)
gestureDetector.onTouchEvent(event)
return true
}
override fun onFling(
downEvent: MotionEvent?,
moveEvent: MotionEvent?,
velocityX: Float,
velocityY: Float
): Boolean {
var result = false
if (downEvent != null && moveEvent != null) {
var diffY: Float = moveEvent.y - downEvent.y
var diffX: Float = moveEvent.x - downEvent.x
val SWIPE_MIN = 100
val SWIPE_Velocity = 100 //TODO WIDTH
if (Math.abs(diffX) > Math.abs(diffY)) {
//RIGHT OR LEFT
if (Math.abs(diffX) > SWIPE_MIN && Math.abs(velocityX) > SWIPE_Velocity) {
if (diffX > 0) {
swipeRight()
} else {
swipeLeft()
}
result = true
}
} else {
//UP OR DOWN
if(Math.abs(diffY) > SWIPE_MIN && Math.abs(velocityY) > SWIPE_Velocity) {
if(diffY > 0) {
swipeUp()
} else {
swipeDown()
}
result = true
}
}
}
return result
}
private fun swipeDown() {
directionDisplayer.text = "Direction: DOWN"
}
private fun swipeUp() {
directionDisplayer.text = "Direction: UP"
}
private fun swipeLeft() {
directionDisplayer.text = "Direction: LEFT"
}
private fun swipeRight() {
directionDisplayer.text = "Direction: RIGHT"
}
MainActivity (only the important):
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestWindowFeature(Window.FEATURE_NO_TITLE)
window.setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
setContentView(R.layout.activity_main)
val canvasImage: ImageView = findViewById(R.id.canvas)
canvasImage.setOnTouchListener(GestureListener(findViewById(R.id.showDirection)))
有人知道如何解决这个问题吗?
【问题讨论】:
-
如果必须是抽象的,您必须在 canvasImage.setOnTouchListener 行中传递实现 GestureListener 的对象
-
你是这个意思吗? "object:GestureListener(...)"
-
是的,就像这样,你可以做 object:GestureListener(){//那里你可以覆盖方法}
-
嗯,在 Kotlin 中有点不同,所以我认为帮助那些拥有第一门编程语言的人也应该没问题
标签: java android kotlin listener motion