How to handle multiple button clicks in a specific pattern?

Viewed 19

I have 3 buttons button 1, button 2 and button 3 the order to click this button should be button 3, button 1, button 2? on completing the pattern in correct manner I want a toast that pattern is correct.

If anyone can help me it would be great? What I have done so far is

MainActivity.java

private final String patternButtonsText = "123";
private String result = "";
int noOfBtns = patternButtonsText.length();
final Button[] btns = new Button[noOfBtns];

for (int i = 0; i < noOfBtns; i++) {
   btns[i] = new Button(getContext());
   btns[i].setText(patternButtonsText.substring(i, i + 1));
   if (isActive) {
      LinearLayout ll = view.findViewById(R.id.btnlay);
      ll.addView(btns[i]);
   }
   final int j = i;
   btns[i].setOnClickListener(v -> {
   if (j == result.length()) {
      result = result + btns[j].getText().toString();
      if(result.length() == patternButtonsText.length()) {
          Toast.makeText(getContext(), "All buttons clicked", Toast.LENGTH_SHORT).show();
   }
  }
 });
}

activity_main.xml

<LinearLayout
        android:id="@+id/btnlay"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:clickable="true"
        android:alpha="0"
        android:orientation="horizontal"
        android:visibility="visible"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/about_tool_bar" />

With this code I am able to follow only one pattern that is 123 and I want 312 sequence

0 Answers
Related