【Android开发经验】-- 如何防止短时间内频繁点击按钮

        如果你想防止用户频繁点击按钮或摇动,可以使用以下方法解决。

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="你不能频繁点击我,不信你试试"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

MainActivity文件

        以下示例1s内不能重复点击按钮

public class MainActivity extends AppCompatActivity {
    private static long lastClickTime = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        TextView textView = (TextView) findViewById(R.id.text);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isFastDoubleShake()){
                    textView.setText("点击成功");
                }else{
                    textView.setText("点击太频繁,稍后再试");                }
            }
        });
    }

    //    防止短时间重复摇动
    public static boolean isFastDoubleShake() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if ( 0 < timeD && timeD < 1000) {
            return false;
        }
        lastClickTime = time;
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/Tir_zhang/article/details/130661305