Ad

Multiple Button Click Event

I have two buttons and each button has each function, but also I would like to add another function when the user clicks these buttons at the same time. Here is my code:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button button1, button2;
private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button1 = findViewById(R.id.button1);
    button2 = findViewById(R.id.button2);
    textView = findViewById(R.id.textView);
    button1.setOnClickListener(this);
    button2.setOnClickListener(this);
}
private long mLastClickTime = 0;

@Override
public void onClick(View v) {
    if (System.currentTimeMillis() - mLastClickTime < 1000) {
        textView.setText("Double Action");
        SPLogger.logMassage("Same", (System.currentTimeMillis() - mLastClickTime) + "");
        return;
    }
    mLastClickTime = System.currentTimeMillis();
    SPLogger.logMassage("notSame", System.currentTimeMillis() + "");

    if (v.getId() == R.id.button1) {
        textView.setText("Only First Action");
    } else if (v.getId() == R.id.button2) {
        textView.setText("Only Second Action");

    }
}
}

This code working almost, but I have one little issue. When I click for example the first button quickly, it's working like same time action. Can anyone tell me what's wrong in my code? also What's the best way to check same time click in Android? Thanks

Ad

Answer

you must check if the second click is from the other button than the first click, so you have to keep in a variable the last clicked button. Example

private long mLastClickTime = 0;
private int mLastClickedID = -1;

@Override
public void onClick(View v) {
    if (System.currentTimeMillis() - mLastClickTime < 1000 && mLastClickedID !=v.getId()) {
        textView.setText("Double Action");
        SPLogger.logMassage("Same", (System.currentTimeMillis() - mLastClickTime) + "");
        return;
    }
    mLastClickTime = System.currentTimeMillis();
    mLastClickedID = v.getId()
    SPLogger.logMassage("notSame", System.currentTimeMillis() + "");

    if (v.getId() == R.id.button1) {
        textView.setText("Only First Action");
    } else if (v.getId() == R.id.button2) {
        textView.setText("Only Second Action");

    }
}
Ad
source: stackoverflow.com
Ad