具有多种类型行布局的ListView-BaseAdapter在Android中无法正常工作



Hi下面是我的baseadapter类,但它不能正常工作:

private static class MyBaseAdapter extends BaseAdapter {
        private Context context;
        private LayoutInflater inflater;

        private MyBaseAdapter(Context context, FlipViewController controller) {
            inflater = LayoutInflater.from(context);
            this.context = context;
        }
        @Override
        public int getCount() {
            return Globals.list_album.size();
        }
        @Override
        public Object getItem(int position) {
            return position;
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View layout = convertView;
            if (convertView == null )
            {
                if (Globals.list_album.get(position).no_of_images == 1) {
                    layout = inflater.inflate(R.layout.single_image_adapter, null);
                }
                else if(Globals.list_album.get(position).no_of_images == 2) {
                    layout = inflater.inflate(R.layout.two_image_adapter, null);
                }
                else if(Globals.list_album.get(position).no_of_images == 3) {
                    layout = inflater.inflate(R.layout.three_image_adapter, null);
                }
                else if(Globals.list_album.get(position).no_of_images == 4) {
                    layout = inflater.inflate(R.layout.four_image_adapter, null);
                }
                else if(Globals.list_album.get(position).no_of_images == 5) {
                    layout = inflater.inflate(R.layout.five_image_adapter, null);
                }   
            }
            return layout;
        }
    }

我想根据Globals.list_album中每个位置的图像数量加载布局。但它不能正常工作。它不适用于no_of_images=5和2,因为我在列表中有这样的值。目前,no_of_images的值为4,3,1,2和5。因此,它应该显示布局four_image_adapter、three_image_adapter,one_image_aapter、two_image_adapter和five_image_address。但它显示四个图像适配器、三个图像适配器,一个图像适配器和四个图像和三个图像。根据图像的数量,所有布局都具有图像视图。有人能告诉我该做什么吗?

由于不同的行需要不同的布局,请使用以下方法

getViewTypeCount()-返回行类型的信息。

getItemViewType(int position)-返回基于位置应使用的布局类型的信息

使用getItemViewType,您可以定义需要使用的布局。

像这个

public static final int TYPE_1 = 1;
public static final int TYPE_2 = 2;
public int getItemTypeCount(){
     return 5;
}
public int getItemType(int position){
    // Your if else code and return type ( TYPE_1 to TYPE_5 )
}
public View getView(int position, View convertView, ViewGroup parent){
    // Return the right kind of view based on getItemType(position)
    int type = getItemType(position);
    if(type == TYPE_1){
        // create (or reuse) TYPE_1 view
    } else if() {
    }......
    return myView;
}

样品

http://android.amberfog.com/?p=296

http://www.survivingwithandroid.com/2014/08/android-listview-with-multiple-row.html

最新更新