我在视野中使用了两个按钮。同时单击两个按钮时,它将一次进入不同的活动。怎么避免这个?
我试过这样,但它不起作用请保存....
public class MenuPricipalScreen extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_principal_layout);
findViewById(R.id.imageView2).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
disable(findViewById(R.id.imageView3));
Intent intent = new Intent(MenuPricipalScreen.this,
SelectYourLanguageVideo.class);
startActivity(intent);
}
});
findViewById(R.id.imageView3).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
disable(findViewById(R.id.imageView2));
Intent intent = new Intent(MenuPricipalScreen.this,
CategoryScreen.class);
intent.putExtra("request", "false");
startActivity(intent);
}
});
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
((ImageView) findViewById(R.id.imageView3)).setEnabled(true);
((ImageView) findViewById(R.id.imageView2)).setEnabled(true);
((ImageView) findViewById(R.id.imageView3)).setClickable(true);
((ImageView) findViewById(R.id.imageView2)).setClickable(true);
((ImageView) findViewById(R.id.imageView3)).setFocusable(true);
((ImageView) findViewById(R.id.imageView2)).setFocusable(true);
}
private void disable(View v) {
Log.d("TAG", "TAG" + v.getId());
v.setEnabled(false);
v.setClickable(false);
v.setFocusable(false);
}
}
谢谢,
答案 0 :(得分:98)
避免多次点击的标准方法是保存最后点击的时间,并避免在1秒(或任何时间跨度)内点击其他按钮。 例如:
// Make your activity class to implement View.OnClickListener
public class MenuPricipalScreen extends Activity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
// setup listeners.
findViewById(R.id.imageView2).setOnClickListener(MenuPricipalScreen.this);
findViewById(R.id.imageView3).setOnClickListener(MenuPricipalScreen.this);
...
}
.
.
.
// variable to track event time
private long mLastClickTime = 0;
// View.OnClickListener.onClick method defination
@Override
public void onClick(View v) {
// Preventing multiple clicks, using threshold of 1 second
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
// Handle button clicks
if (v == R.id.imageView2) {
// Do your stuff.
} else if (v == R.id.imageView3) {
// Do your stuff.
}
...
}
.
.
.
}
答案 1 :(得分:36)
您可以在主题中使用此android:splitMotionEvents="false"
和android:windowEnableSplitTouch="false"
来禁用应用中的多点触控。
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
...
<item name="android:splitMotionEvents">false</item>
<item name="android:windowEnableSplitTouch">false</item>
</style>
答案 2 :(得分:6)
您没有正确的关注点分离(MVP或任何风格),因此您将代码放入Activity / Fragment
如果你无法正确处理这个问题,至少不要使用非确定性解决方案(比如计时器)。
使用您已有的工具,假设您有以下代码:
//Somewhere in your onCreate()
Button myButton = findViewById…
myButton.setOnClickListener(this);
// Down below…
@Override
public void onClick(View view) {
if (myButton.isEnabled()) {
myButton.setEnabled(false);
// Now do something like…
startActivity(…);
}
}
现在......在你的逻辑中一个完全不同的地方,例如,你的onCreate或你的onResume或任何地方,你知道你希望你的按钮再次工作......
myButton.setEnabled(true);
enableMyButton();
或disableMyButton()
视情况而定。 因为它是内置的。 因为按钮会尊重它的状态(如果你有一个正确的状态列表,它会改变你的外观,因为它总是你所期望的)。此外,因为测试充满模拟的演示者比在代码中永久增长的完整活动更容易。
答案 3 :(得分:2)
对于Kotlin用户
object AppUtil {
var mLastClickTime=0L
fun isOpenRecently():Boolean{
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000){
return true
}
mLastClickTime = SystemClock.elapsedRealtime()
return false
}
}
在“活动”或“片段”中或任何地方
只需添加这一行条件
if(isOpenRecently()) return
示例:
fun startHomePage(activity: Activity){
if(isOpenRecently()) return //this one line enough
val intent= Intent(activity,MainActivity::class.java)
activity.startActivity(intent)
}
答案 4 :(得分:2)
如果您使用的是kotlin,请按照以下步骤创建扩展乐趣:
fun View.clickWithDebounce(debounceTime: Long = 1200L, action: () -> Unit) {
this.setOnClickListener(object : View.OnClickListener {
private var lastClickTime: Long = 0
override fun onClick(v: View) {
if (SystemClock.elapsedRealtime() - lastClickTime < debounceTime) return
else action()
lastClickTime = SystemClock.elapsedRealtime()
}
})
}
现在在任何视图上只需调用:
view.clickWithDebounce{
...
}
答案 5 :(得分:1)
您可以尝试我的小型图书馆,它可以使用与Shivanand&#39;相同的方法提供您想要的内容。解。 https://github.com/RexLKW/SClick
答案 6 :(得分:1)
这是一个可以消除View
和MenuItem
的点击次数的类。
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar.OnMenuItemClickListener;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
/**
* Debounce's click events to prevent multiple rapid clicks.
* <p/>
* When a view is clicked, that view and any other views that have applied {@link #shareDebounce} to them,
* will have subsequent clicks ignored for the set {@link #DEBOUNCE_DURATION_MILLIS duration}.
*/
public final class ClickEvent {
private static final long DEBOUNCE_DURATION_MILLIS = 1000L;
private long debounceStartTime = 0;
/**
* Wraps the provided {@link OnClickListener OnClickListener} in a {@link ClickEvent}
* that will prevent multiple rapid clicks from executing.
* <p/>
* Usage:
* <pre>View.setOnClickListener(ClickEvent.debounce((OnClickListener) v -> // click listener runnable))</pre>
*/
public static OnClickListener debounce(@NonNull OnClickListener onClickListener) {
return new ClickEvent().wrapOnClickListener(onClickListener);
}
/**
* Wraps the provided {@link OnMenuItemClickListener OnMenuItemClickListener} in a
* that will prevent multiple rapid clicks from executing.
* <p/>
* Usage:
* <pre>MenuItem.setOnClickListener(ClickEvent.debounce((OnMenuItemClickListener) v -> // click listener runnable))</pre>
*/
public static OnMenuItemClickListener debounce(@NonNull OnMenuItemClickListener onClickListener) {
return new ClickEvent().wrapOnClickListener(onClickListener);
}
/**
* Allows the debounce to be shared between views to prevent multiple rapid clicks between views.
* <p/>
* Usage:
* <pre>
* ClickEvent clickEvent = new ClickEvent();
* View1.setOnClickListener(clickEvent.shareDebounce((OnClickListener) v -> // click listener runnable for View1))
* View2.setOnClickListener(clickEvent.shareDebounce((OnClickListener) v -> // click listener runnable for View2))
* </pre>
*/
public OnClickListener shareDebounce(@NonNull OnClickListener listener) {
return wrapOnClickListener(listener);
}
/**
* Allows the debounce to be shared between views to prevent multiple rapid clicks between views.
* Usage:
* <pre>
* ClickEvent clickEvent = new ClickEvent();
* MenuItem1.setOnClickListener(clickEvent.shareDebounce((OnMenuItemClickListener) v -> // click listener runnable for MenuItem1))
* MenuItem2.setOnClickListener(clickEvent.shareDebounce((OnMenuItemClickListener) v -> // click listener runnable for MenuItem2))
* </pre>
*/
public OnMenuItemClickListener shareDebounce(@NonNull OnMenuItemClickListener listener) {
return wrapOnClickListener(listener);
}
public void setDebounceStartTime() {
debounceStartTime = SystemClock.elapsedRealtime();
}
public boolean isThrottled() {
return SystemClock.elapsedRealtime() - debounceStartTime < DEBOUNCE_DURATION_MILLIS;
}
private OnClickListener wrapOnClickListener(@NonNull OnClickListener onClickListener) {
if (onClickListener instanceof OnThrottledClickListener) {
throw new IllegalArgumentException("Can't wrap OnThrottledClickListener!");
}
return new OnThrottledClickListener(this, onClickListener);
}
private OnMenuItemClickListener wrapOnClickListener(@NonNull OnMenuItemClickListener onClickListener) {
if (onClickListener instanceof OnThrottledClickListener) {
throw new IllegalArgumentException("Can't wrap OnThrottledClickListener!");
}
return new OnThrottledClickListener(this, onClickListener);
}
private static class OnThrottledClickListener implements OnClickListener, OnMenuItemClickListener {
private final ClickEvent clickEvent;
private OnClickListener wrappedListener;
private OnMenuItemClickListener wrappedMenuItemClickLister;
OnThrottledClickListener(@NonNull ClickEvent clickEvent, @NonNull OnClickListener onClickListener) {
this.clickEvent = clickEvent;
this.wrappedListener = onClickListener;
}
OnThrottledClickListener(@NonNull ClickEvent clickEvent, @NonNull OnMenuItemClickListener onClickListener) {
this.clickEvent = clickEvent;
this.wrappedMenuItemClickLister = onClickListener;
}
@Override
public void onClick(View v) {
if (clickEvent.isThrottled()) {
return;
}
wrappedListener.onClick(v);
clickEvent.setDebounceStartTime();
}
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
if (clickEvent.isThrottled()) {
return false;
}
clickEvent.setDebounceStartTime();
return wrappedMenuItemClickLister.onMenuItemClick(menuItem);
}
}
}
答案 7 :(得分:1)
在Kotlin中执行此操作的简单方法是使用:
//When you need to disable the button
btn.isEnabled = false
//When you need to enable the button again
btn.isEnabled = true
答案 8 :(得分:0)
A&#34;更好&#34;实践是像这样使用onClickListener - &GT;
OnClickListener switchableListener = new OnClickListener(@Override
public void onClick(View arg0) {
arg0.setOnClickListener(null);
(or) use the view directly as a final variable in case of errors
ex :
textView.setOnClickListener(null);
// Some processing done here
Completed , enable the onclicklistener arg0.setOnClickListener(switchableListener);
});
这应该可以解决问题及其处理事情的简单方法
答案 9 :(得分:0)
对于任何使用数据绑定的人:
@BindingAdapter("onClickWithDebounce")
fun onClickWithDebounce(view: View, listener: android.view.View.OnClickListener) {
view.setClickWithDebounce {
listener.onClick(view)
}
}
object LastClickTimeSingleton {
var lastClickTime: Long = 0
}
fun View.setClickWithDebounce(action: () -> Unit) {
setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View) {
if (SystemClock.elapsedRealtime() - LastClickTimeSingleton.lastClickTime < 500L) return
else action()
LastClickTimeSingleton.lastClickTime = SystemClock.elapsedRealtime()
}
})
}
<androidx.appcompat.widget.AppCompatButton
..
android:text="@string/signup_signin"
app:onClickWithDebounce="@{() -> viewModel.onSignUpClicked()}"
... />
答案 10 :(得分:0)
对于Xamarin用户,我创建了一个解决方案,该解决方案将按钮类子类化:
using Android.Content;
using Android.Runtime;
using Android.Util;
using Android.Widget;
using System;
using System.Threading.Tasks;
namespace MyProject.Droid.CustomWidgets
{
public class ButtonSingleClick : Button
{
private bool _clicked = false;
public int _timer = 700;
public new EventHandler Click;
protected ButtonSingleClick(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public ButtonSingleClick(Context context) : base(context)
{
base.Click += SingleClick;
}
public ButtonSingleClick(Context context, IAttributeSet attrs) : base(context, attrs)
{
base.Click += SingleClick;
}
public ButtonSingleClick(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
{
base.Click += SingleClick;
}
public ButtonSingleClick(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes)
{
base.Click += SingleClick;
}
private void SingleClick(object sender, EventArgs e)
{
if (!_clicked)
{
_clicked = true;
Click?.Invoke(this, e);
Task.Run(async delegate
{
await Task.Delay(_timer);
_clicked = false;
});
}
}
}
}
答案 11 :(得分:0)
第一:
In [1]: import numpy as np
In [2]: arr = np.array([(1,2,3),(4,5,6), (7,8,9)], dtype=np.dtype([('AgentID', '<i8'), ('CellID', '<i4'), ('Hybridization', '<f4')]))
In [3]: arr['Hybridization']
Out[3]: array([3., 6., 9.], dtype=float32)
现在只需在onCLick方法主体中的任何地方或您需要的任何地方调用此方法即可
public class ClickValidate {
public static long lastClickTime;
public static boolean isValid()
{
long current=System.currentTimeMillis();
long def = current - lastClickTime;
if (def>1000)
{
lastClickTime = System.currentTimeMillis();
return true;
}
else
return false;
}
}
答案 12 :(得分:0)
我已经为这个问题找到了自己的解决方案。虽然,用户按下按钮(垃圾邮件按下它),它仍然会触发一次。
这是针对 Kotlin 的,因为我将使用协程。按下按钮后,我们将其禁用,然后在作业完成后,启用返回按钮。
<a onClick={() => setNewUser(!newUser)} style={{ color: "#845ec2", cursor: "pointer" }} onClick> //<---This
答案 13 :(得分:0)
如果您必须在 RecyclerView
中的对象之间执行相同操作,您只需将 android:splitMotionEvents="false"
添加到您的 xml 文件内的 View
。就像这样:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/yourRecViewID"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:splitMotionEvents="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layoutAnimation="@anim/layout_animation"/>