-2

I'm trying to get the values from the TextViews in the Listitems, to "sum" and calculate the total (val1+val2+...+valn=total).

The structure: ListView > listItem/RelativeLayout > TextView. The values come from a Custom Adapter.

*I know I need to use a iterator to count the listItem, and obtain the values, but i don't know how to call the rows of listview.

Tsar
  • 170
  • 1
  • 6
  • 20
oldkefka
  • 95
  • 2
  • 9

3 Answers3

1

Since the textViews on the ListView are recycled, which means most/all of them are just what the user sees, you can't use them.

The best way to do it is to perform the calculations on the data that's being used instead.

android developer
  • 114,585
  • 152
  • 739
  • 1,270
  • Yes, and since I think you are new to ListView, I strongly suggest you to watch "the world of ListView" (it's old, but still very useful), and maybe even watch the new RecyclerView lectures, which, according to Google, aims to replace ListView (they called it "ListView 2") . – android developer Nov 10 '14 at 16:47
  • You're right I'm new with the use of "ListView". Thank you – oldkefka Nov 10 '14 at 17:38
1

Ugly, but it works...

private int sumMyIntValues(ListView myList) {
    int sum=0;
    for (int i = 0; i < myList.getCount(); i++) {
        View v = myList.getChildAt(i);
        TextView myView = (TextView) v.findViewById(R.id.myView);
        sum = sum + Integer.parseInt( myView.getText().toString() )
    }
    return sum;
}
Ismael Di Vita
  • 1,806
  • 1
  • 20
  • 35
0

You can access the rows of a list view by calling the adapter and queuing each index. Assuming "myList" is your list:

for (int i = 0; i < myList.getCount(); i++){
    View v = myList.getAdapter().getView(i, null, null);
    TextView txt = v.findViewById(  *idOfYourTextView*   );
    //Do something with the text

}      

Referenced from: Iterate through ListView and get EditText-Field values

Community
  • 1
  • 1
Keith Aylwin
  • 516
  • 4
  • 15