检测双击,即每当用户在任何视图上双击时,如何检测到它,并根据该视图,可以添加一个与之对应的响应。在此显示了一个示例,其中检测到视图上的双击,并相应地以烤面包的形式添加了响应。
第1步:在Android Studio中创建一个空活动。要创建一个,请遵循以下文章-https://www.geeksforgeeks.org/android-how-to-create-start-a-new-project-in-android-studio/。检查所选的主要语言是否为Kotlin。
步骤2:在activity_main.xml中未做任何更改。由于已经存在文本视图,因此双击响应也随之添加。
XML
Kotlin
package org.geeksforgeeks.viewdoubletap
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// In our case, we tap on Text View
val view = findViewById(R.id.tvView)
// Double Click Listener implemented on the Text View
view.setOnClickListener(object : DoubleClickListener() {
override fun onDoubleClick(v: View?) {
Toast.makeText(applicationContext,"Double Click",Toast.LENGTH_SHORT).show()
}
})
}
// Abstract class defining methods to check Double Click where Time Delay
// between the two clicks is set to 300 ms
abstract class DoubleClickListener : View.OnClickListener {
var lastClickTime: Long = 0
override fun onClick(v: View?) {
val clickTime = System.currentTimeMillis()
if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) {
onDoubleClick(v)
}
lastClickTime = clickTime
}
abstract fun onDoubleClick(v: View?)
companion object {
private const val DOUBLE_CLICK_TIME_DELTA: Long = 300 //milliseconds
}
}
}
步骤3:在此步骤中,为双击添加抽象类,并设置将使用抽象类的onClickListener。下面是MainActivity.kt类的代码。
科特林
package org.geeksforgeeks.viewdoubletap
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// In our case, we tap on Text View
val view = findViewById(R.id.tvView)
// Double Click Listener implemented on the Text View
view.setOnClickListener(object : DoubleClickListener() {
override fun onDoubleClick(v: View?) {
Toast.makeText(applicationContext,"Double Click",Toast.LENGTH_SHORT).show()
}
})
}
// Abstract class defining methods to check Double Click where Time Delay
// between the two clicks is set to 300 ms
abstract class DoubleClickListener : View.OnClickListener {
var lastClickTime: Long = 0
override fun onClick(v: View?) {
val clickTime = System.currentTimeMillis()
if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) {
onDoubleClick(v)
}
lastClickTime = clickTime
}
abstract fun onDoubleClick(v: View?)
companion object {
private const val DOUBLE_CLICK_TIME_DELTA: Long = 300 //milliseconds
}
}
}
在仿真器上的输出:
想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处前往由我们的专家精心策划的指南,以使您立即做好行业准备!