如何获取列表视图中的项目以检测单击事件 单击该项目时我的列表视图 OnitemClickListener 正在工作,但我的列表视图包含一个图像和一个按钮,每个按钮都有不同的操作,但我必须在图像操作之前单击两次触发并在触发按钮操作之前单击两次。有没有办法检测图像是否在第一次单击时被单击,然后触发操作。 这是我的列表视图 onItemClick 代码
listView.setOnItemClickListener((parent, view, position, id) -> {
ImageView imgOpen = view.findViewById(R.id.pImage);
imgOpen.setOnClickListener(v -> {
//Action For Image Here
});
Button btnOpen = view.findViewById(R.id.btnOpen);
btnOpen.setOnClickListener(v -> {
//Action For Button Here
});
});
参考:自定义ListView上的setOnItemClickListener
在上面的示例代码中:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object listItem = list.getItemAtPosition(position);
}
});
注意:您应该将 findViewById 移出 onItemClick()
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.AdapterView
class DoubleClickListener(
private val doubleClickThreshold: Long = 300, // time in milliseconds to consider as double-click
private val onSingleClick: (AdapterView<*>, View, Int, Long) -> Unit,
private val onDoubleClick: (AdapterView<*>, View, Int, Long) -> Unit
) : AdapterView.OnItemClickListener {
private val handler = Handler(Looper.getMainLooper())
private var lastClickTime: Long = 0
private var lastPosition: Int = -1
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val currentTime = System.currentTimeMillis()
if (lastPosition == position && (currentTime - lastClickTime) < doubleClickThreshold) {
handler.removeCallbacksAndMessages(null)
onDoubleClick(parent, view, position, id)
} else {
handler.postDelayed({
onSingleClick(parent, view, position, id)
}, doubleClickThreshold)
}
lastClickTime = currentTime
lastPosition = position
}
}
// Usage example:
val listView: ListView = findViewById(R.id.listView)
listView.onItemClickListener = DoubleClickListener(
onSingleClick = { parent, view, position, id ->
// Handle single click
println("Single Clicked on position $position")
},
onDoubleClick = { parent, view, position, id ->
// Handle double click
println("Double Clicked on position $position")
}
)