When Extending An Arrayadapter And Overriding Getview, Is Passing The Resource/textviewresourceid Arguments Completely Redundant?
Solution 1:
super(context, R.layout.list_item_layout, R.id.item_text_inside_layout, items);
the 3rd parameter is usefull when you want to use custom layout for ListView/Gridview.
ArrayAdapter use Object.toString()
to get the value of each item in Listview. It must have a TextView to display. So you have three options here
Use default layout for text item. like
android.R.layout.simple_list_item_1
Use custom layout for text item and provide textViewId to place your data. like
super(context, R.layout.list_item_layout, R.id.item_text_inside_layout, items);
Use custom Adapter, not
ArrayAdapter
. You can extendBaseAdapter
and inflate what view you want
Hope it help !
Solution 2:
Are there any potential benefits (at all) to passing anything else in it's place when you also override getView?
Sure. If you pass your actual layout and TextView
Resource ID, you can let the super.getView()
method handle the View
inflation and assigning the text on a single TextView
. Then your getView()
override would just need to "fill in the blanks".
For example, say we have the following simple list item class:
publicclassItem {
String text;
int imageResId;
publicItem(String text, int imageResId) {
this.text = text;
this.imageResId = imageResId;
}
@OverridepublicStringtoString() {
return text;
}
}
And a simple item layout like so:
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:gravity="center_vertical"><ImageViewandroid:id="@+id/item_image"android:layout_width="wrap_content"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/item_text"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>
Then our ArrayAdapter
subclass could be simply this:
publicclassMyAdapterextendsArrayAdapter<Item> {
publicMyAdapter(Context context, List<Item> items) {
super(context, R.layout.list_item, R.id.item_text, items);
}
@Overridepublic View getView(int position, View convertView, ViewGroup parent) {
Viewv=super.getView(position, convertView, parent);
((ImageView) v.findViewById(R.id.item_image))
.setImageResource(getItem(position).imageResId);
return v;
}
}
Note that we implement a toString()
override in our Item
class to provide the correct String
to ArrayAdapter
.
Post a Comment for "When Extending An Arrayadapter And Overriding Getview, Is Passing The Resource/textviewresourceid Arguments Completely Redundant?"