Implementation of Android's continuous click multiple times function

  1. Draw a button in the layout file (activity_main.xml) with the id bt_click:
<Button
    android:id="@+id/bt_click"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="按钮点击"
    android:textColor="@color/black"
    android:textSize="20sp"/>
  1. Do the following in the MainActivity class:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
    
    //按钮
    private Button bt_click;
    //点击次数
    int count = 3;
    //规定的有效时间
    long time = 3000;
    long[] mHits = new long[count];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化控件
        initView();
    }

    //初始化控件
    private void initView() {
    
    
        bt_click = findViewById(R.id.bt_click);
        bt_click.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
    
    
        switch (v.getId()) {
    
    
            case R.id.bt_click:
                SetButton();
                break;
        }
    }

    //连续点击按钮三次
    private void SetButton() {
    
    
        //每次点击时,数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //为数组最后一位赋值
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - time)) {
    
    
            //数组重新初始化
            mHits=new long[count];
            Toast.makeText(MainActivity.this, "已连续点击" + mHits.length + "次", Toast.LENGTH_SHORT).show();
        }
    }
}

The number of clicks I set is 3, and the effective time is 3 seconds. You can change the number of clicks and effective time according to your needs.
The above is the code to implement the function of continuous clicks.

Guess you like

Origin blog.csdn.net/weixin_58159075/article/details/126642847