问题
In my app, I show data in a list view. It looks as below.

Each row in list view is different (ie., they have a different view structure). But every row is made up of 1 to many subviews (all subview are same ).
Problem: If try to inflate the rows from xml then I need to have xml with 1. 2 subviews 2. 3 subviews 3. 5 subviews and so on
If I try to build the rows dynamically then I wont be able to take advantage of the holder pattern or the views re-usability of Listview. And I will end up building the subviews if the number of subviews, in the returned view is less than required or deleting in case the subviews are more than required.
In a nutshell, how can I have different views in listview which does not hamper view re-usability or holder pattern ?
Edit:
I have extended ArrayAdapter and overriden getView, getViewTypeCount, getItemViewType
@Override
public int getItemViewType(int position) {
return mListItems.get(position).getViewToBeRenderened().getViewId();
}
@Override
public int getViewTypeCount() {
return AppConstants.VwViewTypes.values().length;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final VWListItem listItem = mListItems.get(position);
if(listItem == null || listItem.getViewToBeRenderened() == null){
return convertView;
}
VWView renderingView = listItem.getViewToBeRenderened();
if(convertView == null ){
convertView = renderingView.buildView(mContext.appContext);
}
...
}
This approach worked initially when there were only 2-3 differing row views. For each of these row views i had a different xml layout and corresponding class which would build and inflate.
But now the number of such views is growing and I dont want to have a layout and class for each additional new row view. Instead I would like to reuse existing layouts and class and build on them. If there is a better solution then am open to it as well.
回答1:
when you have to manage different kinds of views you should override getViewTypeCount()
and getItemViewType()
and you will receive a number of convertViews equals to the int returned by getViewTypeCount()
. For instance, If it returns 2 you will get 2 differents convertView
.
回答2:
ListView is supposedly used to relieve the coders of some burden when each row has similar repetitive pattern. Yes, for slight variations getViewType
is the correct choice to implement, but I see a better solution to your problem: you should create your own linearlayout if you have a lot of customization requirement. Remember that listview itself is an expensive object to create. Create a custom linearlayout is not that hard.
来源:https://stackoverflow.com/questions/17566512/best-way-to-build-and-handle-list-view-with-differing-rows