user3424226 user3424226 - 1 year ago 125
Android Question

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(;
final View v = view;
final int position = i;
name.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton group, boolean isChecked) {
EditText quantity = (EditText) v.findViewById(;
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(;

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.

Answer Source

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;

    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download