androidarraylist

Get single integer from list on click


This is my array-list/list.. i want single single value when i click on button and the value from list should be added in total..

[1, 1, 3, 3, 3, 3, 1, 1, 3, 1, 4, 3, -1, 4, 1, 4, 1, 2, 4, 1, 1, 1, 4, 1, 1]

things that i have tried

for (int i = 0; i < Score1.size(); i++) {

              score = Score1.get(i);
              score2 += score;
}

out put:

total﹕ 51

but this thing should happen only on button click.. i tried few things..but when i click button..total comes all together..but i don't want that.

Required output-

total=0
total=1
total=2
total=5
etc...

Solution

  • Declare in Global

    int  i = 0;
    int score = 0;
    

    In your Method

        button.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if(i<Score1.size()){
                                        score = Score1.get(i);
                                        i++;
                                        System.out.println(score); // or any task you want to do
                                        }
                                    }
                                });
    

    In score your addition will be stored after every click.