Android ListView with multiple layouts

前端 未结 3 599
清酒与你
清酒与你 2021-01-18 21:11

I have to show a list with different type of Views. So I have to define a ListView with an Adapter where I have to inflate multiple views. I have gone through example given,

3条回答
  •  情话喂你
    2021-01-18 21:47

    You can look this example adapter. getViewTypeCount method return your different type row. getItemViewType method, if position equals 0 inflate first row layout else inflate other row layout. You can customize this code example.

        import java.util.List;
        import android.app.Activity;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.ArrayAdapter;
    
        /**
         * Created by MustafaS on 9.2.2015.
         */
        public class CustomArrayAdapter extends ArrayAdapter {
    
           @Override
           public int getItemViewType(int position) {
    
              if (position == 0) {
                 return 0;
              }
              else {
                 return 1;
              }
           }
    
           @Override
           public int getViewTypeCount() {
              return 2;
           }
    
           @Override
           public View getView(int position, View convertView, ViewGroup parent) {
              int type = getItemViewType(position);
              if (type == 0) {
                 if (convertView == null) {
                    convertView = LayoutInflater.from(activity).inflate(R.layout.listview_first_row, parent, false);
                    viewHolderFirst = new ViewHolderFirst();
                    convertView.setTag(viewHolderFirst);
                 }
                 else {
                    viewHolderFirst = (ViewHolderFirst) convertView.getTag();
                 }
    
              }
              else {
                 if (convertView == null) {
                    convertView = LayoutInflater.from(activity).inflate(R.layout.listview_other_row, parent, false);
                    viewHolder = new ViewHolder();
    
                 }
                 else {
                    viewHolder = (ViewHolder) convertView.getTag();
                 }
              }
              return convertView;
           }
    
           protected class ViewHolderFirst {
              private RunnableViewPager pager;
              private CircleIndicator   indicator;
           }
    
           protected class ViewHolder {
              private ImageView imageviewRestaurant;
              private TextView  textviewRestaurantName;
              private TextView  textviewType;
              private TextView  textviewPrice;
              private TextView  textviewDistance;
              private ImageView imageviewCall;
              private ImageView imageviewCalendar;
           }
        }
    

提交回复
热议问题