Android: xml layout for a listview with different items

后端 未结 4 1451
礼貌的吻别
礼貌的吻别 2020-11-28 14:18

I\'m reading this tutorial http://android.amberfog.com/?p=296 . I\'d like to create a Listview weith different types of rows. I understand how to create the adapter, but wha

4条回答
  •  忘掉有多难
    2020-11-28 14:47

    You need to override getViewItemType and getViewTypeCount. You will also need to have custom layouts.

    getItemViewType(int position) - returns information which layout type you should use based on position.

    You should have a look at the video in the link.

    http://www.youtube.com/watch?v=wDBM6wVEO70

    private static final int TYPE_ITEM1 = 0;
    private static final int TYPE_ITEM2 = 1;
    private static final int TYPE_ITEM3 = 2; 
    

    Then

    int type;
    @Override
    public int getItemViewType(int position) {
    
        if (position== 0){
            type = TYPE_ITEM1;
        } else if  (position == 1){
            type = TYPE_ITEM2;
        }
        else
        {
             type= TYPE_ITEM3 ;
        }
        return type;
    }
    
     @Override
     public int getViewTypeCount() {
            return 3; 
     }
    @Override  
    public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    LayoutInflater inflater = null;
    int type = getItemViewType(position);
      // instead of if else you can use a case
       if (row  == null) {
        if (type == FIRST_TYPE) {
                //infalte layout of type1
          }
        if (type == SECOND_TYPE) {
                //infalte layout of type2
        }  else {
                //infalte layout of normaltype
     }
    } 
    

提交回复
热议问题