1

I've implemented a listview (where each item is a buttom) and now I want to improve its efficiency by using a ViewHolder. Here is my problem, I dont know where must I override these button's OnClick methods.

This is the getView of my ArrayAdapter:

public View getView(final int position, View convertView, ViewGroup parent) {  
    ViewHolder view;  
    if(convertView==null)  
    {  
        view = new ViewHolder();  
        LayoutInflater inflator = activity.getLayoutInflater();  
        convertView = inflator.inflate(R.layout.layout_opcion, null);  
        view.b_opcion = (Button) convertView.findViewById(R.id.boton_opcion);
        **view.b_opcion.setOnClickListener(new View.OnClickListener() {...});**
        convertView.setTag(view);  
    }  
    else  
    {  
        view = (ViewHolder) convertView.getTag();  
    }
    **view.b_opcion.setOnClickListener(new View.OnClickListener() {...});**
    view.b_opcion.setText(getItem(position));  
    return convertView;  
}  

}

This OnClick method must display some info about the item selected, so here is my question. Can I override this method inside

if(convertView==null) {HERE}

(in order to do that just once)? Or against that, inside this IF there must be just the lines of code which refer to inflating layouts?

dnaranjo
  • 3,647
  • 3
  • 27
  • 41

2 Answers2

0

You want to it after you if statement. Inside the if statement you will only be getting a reference to the UI elements of the View. After the if statement you can then make changes, set listeners etc.

David Scott
  • 1,666
  • 12
  • 22
0

I would put a parameter in view holder which defines some identification of the row (such as an Id or position)

set this information outside of the if's you are using (just before or after view.b_opcion.setText(...

I would define a listener class that implemets OnClickListener, and attach the same single instance to all of the views inside the first if statement.

In onlick listener you can call getTag to view, convert the object to viewholder, and then get your id/position from viewholder. After that you can reach to the object and do what ever you want on the data you have: the view, the adapter item etc.

Siyamed
  • 495
  • 2
  • 11