mdv mdv - 1 month ago 5
Android Question

question on getView()

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;
}

}

JRL JRL
Answer

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.

Comments