tags:

views:

45

answers:

1

Can anyone possible explain what the following code does?

  public View getView(int position, View convertView, ViewGroup parent) {

   // TODO Auto-generated method stub
   View myView = null;
   try {
    myView = convertView;
    if (null == myView) {
     LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

     myView = li.inflate(R.layout.demographic_list_item, null);

    }
    if (mScan_listItems[position] != null) {
     // read the values and attach them.
     TextView tv1 = (TextView) myView
       .findViewById(R.id.DemoGraphicItem_Text);

     tv1.setText(mScan_listItems[position]);

    }

   } catch (Exception e) {
    e.printStackTrace();
   }

   return myView;
  }

 }
A: 

The Adapter.getView docs give some indication of the use of getView:

public abstract View getView (int position, View convertView, ViewGroup parent)

Get a View that displays the data at the specified position in the data set. You can either create a View manually or inflate it from an XML layout file. When the View is inflated, the parent View (GridView, ListView...) will apply default layout parameters unless you use inflate(int, android.view.ViewGroup, boolean) to specify a root view and to prevent attachment to the root.

position

The position of the item within the adapter's data set of the item whose view we want.

convertView

The old view to reuse, if possible. Note: You should check that this view is non-null and of an appropriate type before using. If it is not possible to convert this view to display the correct data, this method can create a new view.

parent

The parent that this view will eventually be attached to

Returns

A View corresponding to the data at the specified position.


getView will get called for every item in your dataset. From the Adapter API docs:

An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set.

JRL
Paraphrased: getView is called for every list item that becomes visible on your screen. If 7 items are visible, getView will be called 7 times, once for each item. Inflating Views is costly, and there is no point in re-inflating a list item. convertView is the current list item being updated with getView. The first time the item is drawn, convertView is null. Subsequent times, it will not be null and the code will not re-inflate it. The bottom portion is simply updating some text on convertView.
Andrew
thanx a lot Andrew...I have some doubt in this file..shall I mail you and ask the doubt? can u pls give ur e-mail id?
mdv