在图片上,我想设置一个点击监听器,以便在点击后执行操作。
即使单击一下,下面的代码也会被多次调用。
我该怎样防止这种情况? (我使用过onTouchListener但结果是相同的......)
Image1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("DisplayImage", "on click");
DisplayOneImage doi=new DisplayOneImage(DisplayImage.this,"Filtered image 1");
doi.show();
}
});
xml文件:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
>
<!-- \/ \/ \/ \/ To be deleted Menu \/ \/ \/ \/ -->
<!--include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" /-->
<!-- /\ /\ /\ /\ To be deleted Menu /\ /\ /\ /\ -->
<LinearLayout
android:id="@+id/img_original"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Original Image:" />
<ImageView
android:id="@+id/initial_photo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
</ImageView>
</LinearLayout>
</ScrollView>
答案 0 :(得分:5)
我在OnClickListener
方法中将null
设置为onClick
,如下所示。
Image1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("DisplayImage", "on click");
DisplayOneImage doi=new DisplayOneImage(DisplayImage.this,"Filtered image 1");
doi.show();
v.setOnClickListener(null);//Remove setOnClickListener
}
});
答案 1 :(得分:0)
另一种更具侵入性的选择
Image1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("DisplayImage", "on click");
DisplayOneImage doi=new DisplayOneImage(DisplayImage.this,"Filtered image 1");
doi.show();
Image1.setVisibility(View.GONE);
}
});
答案 2 :(得分:0)
使用此:
Image1.setOnClickListener(new View.OnClickListener() {
boolean clicked = false;
public void onClick(View v) {
if (!clicked) {
Log.d("DisplayImage", "on click");
DisplayOneImage doi=new DisplayOneImage(DisplayImage.this,"Filtered image 1");
doi.show();
clicked = true;
}
}
});
答案 3 :(得分:0)
如果某人想要一个onClickListener
,只能每秒(1000毫秒)单击一次:
private boolean clicked = false;
element.setOnClickListener(v -> {
if(!clicked){
clicked = true;
doSomething(v.getSomething());
new Handler().postDelayed(() -> clicked = false, 1000);
}
});