andrdoid ListView重写Adapter

在很多项目中都会用到ListView,但基本都需要进行重写Adapter,但每次都是会找好半天,写在这儿方便以后copy~~

xml定义一个ListView

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:background="#ffffff"
        android:padding="5dip" >
        </ListView>
</LinearLayout>

重写Adapter

public class SmsMmsAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private Context mContext;
		private MessageBase mMessageBase;
		private MessageMms mMessageMms;
		private MessageSms mMessageSms;
		private ViewHolder mViewHolder;

		public SmsMmsAdapter(Context pContext) {
			mContext = pContext;
			mInflater = LayoutInflater.from(pContext);
			mMessageBase = new MessageBase();
			mMessageMms = new MessageMms();
			mMessageSms = new MessageSms();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mMessageList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			mMessageBase = mMessageList.get(position);
			if (convertView == null) {
				mViewHolder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.list_say_he_item,
						parent, false);
				
			} else {
				if (convertView.getId() != R.id.mListSayHeItem) {
					convertView = mInflater.inflate(
							R.layout.list_say_he_item, parent, false);
					mViewHolder = new ViewHolder();
				} else {
						mViewHolder = (ViewHolder) convertView.getTag();
				}
			}
			mMessageBase = mMessageList.get(position);
			mViewHolder.mBody = (TextView) convertView
					.findViewById(R.id.mMmsContent);
			mViewHolder.mMmsBitmap = (ImageView) convertView.findViewById(R.id.mMmsBitmap);
			mViewHolder.mMmsSubject = (TextView) convertView.findViewById(R.id.mMmsSubject);
			mViewHolder.mMmsSendTime = (TextView) convertView.findViewById(R.id.mMmsSendTime);
			convertView.setTag(mViewHolder);
			return convertView;
		}
		
		public final class ViewHolder {
			public TextView mBody;
			public ImageView mMmsBitmap;
			public TextView mMmsSubject;
			public TextView mMmsSendTime;
		}
	}


其中ListView的大小是由mMessageList的大小来决定的,convertView通过setTag和getTag方法来实现重用机制,在重用的过程中,通过convertView.getId来和期望的布局Id进行比较,如果是则进行重用,如果不是则重新从布局中读取,这个方法只适合在ListView中的每个Item并不是完全一样,比如第一行和别的不一样,mListSayHeItem是list_say_he_item中最外外边的那个布局Id.

 

发布了115 篇原创文章 · 获赞 5 · 访问量 51万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览