Search code examples
androidbuttonstorepressed

How to store button pressed for android app?


I am making an android app that needs the user to enter a 4 digit pin from the buttons I made and later on confirm the pin. I figured I would be able to store the pin as an array.

My question is, how do I store the button pressed?

Here is what I have come up with so far

public class EnterPin extends Activity 

{

public int[] pin = new int[4];

public void PinEnterd(View view)

{

int i;

for(i = 0; i < 4; i++ )

{

pin = 

}


}

}

Solution

  • You need declare a variable to mark the next position of the pin. In the case of the code below, you can save the next position of your pin to ctr.

    public int[] pin = new int[4];
    int ctr = 0; //add this to mark the index of your pin
    
    public void PinEnterd(View view)
    {
        Button btnPressed = (Button) view; //get access to the button
        int value = Integer.parseInt(btnPressed.getText().toString()); //get the value of the button
        pin[ctr++] = value; //save inputted value and increment counter. next position after 0 is 1.
    }
    
    • When you inputted the first pin and the value of ctr is 0, the inputted pin will be save to pin[0].
    • When you inputted the first pin and the value of ctr is 1, the inputted pin will be save to pin[1].
    • When you inputted the first pin and the value of ctr is 2, the inputted pin will be save to pin[2].
    • When you inputted the first pin and the value of ctr is 3, the inputted pin will be save to pin[3].