How to get the sum of a listview in android studio?

1

To date I have been able to add elements to my list, but I do not know the method so that in a textview the total value of my list is reflected, I have the source code in case someone wants to try it

public class MainActivity extends AppCompatActivity {

    private ArrayList<String> telefonos;
    private ArrayAdapter<String> adaptador1;
    private ListView lv1;
    private EditText et1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        telefonos=new ArrayList<String>();
        telefonos.add("50");
        telefonos.add("50");
        telefonos.add("100");
        adaptador1=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,telefonos);
        lv1=(ListView)findViewById(R.id.listView);
        lv1.setAdapter(adaptador1);

        et1=(EditText)findViewById(R.id.editText);

        lv1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                final int posicion=i;

                AlertDialog.Builder dialogo1 = new AlertDialog.Builder(MainActivity.this);
                dialogo1.setTitle("¡ Atención !");
                dialogo1.setMessage("¿ Borrar el registro ?");
                dialogo1.setCancelable(false);
                dialogo1.setPositiveButton("Sí", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogo1, int id) {
                        telefonos.remove(posicion);
                        adaptador1.notifyDataSetChanged();
                    }
                });
                dialogo1.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogo1, int id) {
                    }
                });
                dialogo1.show();

                return false;
            }
        });
    }

    public void agregar(View v) {
        telefonos.add(et1.getText().toString());
        adaptador1.notifyDataSetChanged();
        et1.setText("");
    }
}
    
asked by Cesar Brooks 14.08.2017 в 21:20
source

1 answer

1

If you want to get the total number of items you have in a list and, considering that the variable that contains your list is called listView , you could use the following code:

int total = listView.getAdapter().getCount();

which will return the number of items that the list contains.

If you want the value to be reflected in a TextView , then you simply have to add that value to it.

TextView textView = (TextView) findViewById(R.id.tuTextView);
textView.setText("" + total);
    
answered by 14.08.2017 в 21:23