Search code examples
androidlistviewadapterfindviewbyid

Android call findViewById from adapter custom class


Good afternoon,

So I have a custom ListView with a custom Adapter that has an item that is a checkbox for each row. In my getView I implemented setOnCheckedChangeListener and the onCheckedChanged handlers for my checkbox.

Now, the problem is:

Whenever I check/uncheck one of items of the list I would like to update an external TextView with the values I want (assume that for each item there is a price associated so I want to show below the list the total price).

How am I supposed to reach the "external" view from the getView of adapter? What other workaround do I have?

I leave here some part of my code on the getView function of my custom adapter:

CheckBox name = (CheckBox) view.findViewById(R.id.product);
    name.setText(content[i][0]);
    final View v = view;
    final int position = i;
    name.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton group, boolean isChecked) {
            setCheckedItem(position);
            EditText quantity = (EditText) v.findViewById(R.id.product_quantity);
            content[position][3] = quantity.getText().toString();
            Iterator<String> it = getCheckedItems().values().iterator();
            Double total = 0.0;
            for (int i=0;i<getCheckedItems().size();i++){
                Integer quantity_p = Integer.parseInt(getItem(position)[3]);
                Double price = Double.parseDouble(getItem(position)[2]);
                total += quantity_p*price;
            }
            TextView total_price = (TextView) findViewById(R.id.total_products_price);
            total_price.setText(total.toString());
        }
    });

Notice the last two lines: I know I can't call the findViewById but I don't know what to do by now. Any suggestions would be good, thank you.


Solution

  • You can pass your TextView to an Adapter in constructor. After this you can have a private static class which will implement CompoundButton.OnCheckedChangedListener like this:

    private static class MyOnCheckedChangedListener 
                         implements CompoundButton.OnCheckedChangedListener {
        TextView myView;
        public MyOnCheckedChangedListener (TextView viewToChange) {
             myView = viewToChange;
        }
    
        @Override
        public void onCheckedChanged(CompoundButton group, 
                                     boolean isChecked) { ... }
    }
    

    After this just setOnCheckedChangedListener new MyOnCheckedChangedListener (myTextView) (the one you passed to Adapter) and you're ready to go.