ITEEDU

BaseAdatper抽象类

BaseAdapter
extends Object
implements ListAdapterSpinnerAdapter

实现方法如下。

public int getCount() 
public Object getItem(int position)
public long getItemId(int position)
public View getView(int position, View convertView, ViewGroup parent)

类中要有一个列表对象,存储list的各项的数据。所以还一个构造函数对这个列表对象赋值,或一个赋值方法。

基本结构

	protected ArrayList<Tweet> mTweets;
	private Context mContext;
	public TweetArrayAdapter(Context context,ArrayList<Tweet> tweets) {
		mTweets = tweets;
		mContext = context;
	}

	@Override
	public int getCount() {
		return mTweets.size();
	}

	@Override
	public Object getItem(int position) {
		return mTweets.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	private static class ViewHolder {
		public TextView tweetUserText;
	...
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view=null;
		if (convertView == null) {//为空创建,并不是每次都要创建,所以这步很有必要
			view = mInflater.inflate(R.layout.tweet, parent, false);
			ViewHolder holder = new ViewHolder();
			holder.tweetUserText = (TextView) view
					.findViewById(R.id.tweet_user_text);
			...
			view.setTag(holder);
		} else {
			view = convertView;
		}

		ViewHolder holder = (ViewHolder) view.getTag();
		Tweet tweet = mTweets.get(position);
		holder.tweetUserText.setText(tweet.screenName);
	...//设置view项内容
		return view;
	}