新浪微博客户端开发之adapter

新浪微博客户端开发之adapter

2013年11月23日 新浪微博客户端系列博客记录

之前获取首页微博列表还没有介绍adapter,关于adapter可以分出来一块来讲,用过ListView的童鞋们肯定对adapter不会陌生,下面是Android提供的一些Adapter,适用与一些简单的数据填充。

  • BaseAdapter是一个抽象类,继承它需要实现较多的方法,所以也就具有较高的灵活性;
  • ArrayAdapter支持泛型操作,最为简单,只能展示一行字。
  • SimpleAdapter有最好的扩充性,可以自定义出各种效果。
  • SimpleCursorAdapter可以适用于简单的纯文字型ListView,它需要Cursor的字段和UI的id对应起来。如需要实现更复杂的UI也可以重写其他方法。可以认为是SimpleAdapter对数据库的简单结合,可以方便地把数据库的内容以列表的形式展示出来。

到了新浪微博这里就需要自定义Adapter了,使用Android提供的adapter已经不能满足需求了,目前小巫所开发的有以下自定义adapter:

AppsListAdaper:用于显示联想搜索得到的app列表。
CommentListAdapter:用于显示评论列表。
FaceListAdapter:用于显示表情列表。
MSGAdapter:用于显示消息页面列表。
UsersListAdaper:用于显示联想搜索得到的User列表。
WeiboListAdapter:用于显示微博列表(首页、收藏、@我的)。
WeiboListNoMoreAdapter:在WeboListAdapter基础上去掉“更多”的adapter。


首页界面效果:


今天我只介绍WeiboListAdapter

/xiaowu_twitter/src/com/wwj/sina/weibo/adapters/WeiboListAdapter.java


WeiboListAdapter是稍显复杂的,因为它要显示的数据比较多,涉及到微博图片的显示,转发内容的显示,先来看看代码先吧。

package com.wwj.sina.weibo.adapters;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wwj.sina.weibo.R;
import com.wwj.sina.weibo.interfaces.Const;
import com.wwj.sina.weibo.library.StorageManager;
import com.wwj.sina.weibo.library.WeiboManager;
import com.wwj.sina.weibo.object.Status;
import com.wwj.sina.weibo.util.Tools;
import com.wwj.sina.weibo.workqueue.DoneAndProcess;
import com.wwj.sina.weibo.workqueue.task.ParentTask;

/**
 * 微博列表适配器 主要用来显示首页、提示我的、收藏微博列表
 * 
 * @author wwj
 * 
 */
public class WeiboListAdapter extends BaseAdapter implements Const,
		DoneAndProcess {
	protected Activity activity;
	protected int type;
	protected LayoutInflater layoutInflater;
	protected List<Status> statuses;

	public WeiboListAdapter(Activity activity) {
		this.activity = activity;
	}

	/**
	 * 需要传入一个已经封装微博数据的List对象 type表示
	 * 
	 * @param activity
	 * @param statuses
	 * @param type
	 *            表示处理的微博数据类型,在Const中定义相关常量
	 */
	public WeiboListAdapter(Activity activity, List<Status> statuses, int type) {
		this.activity = activity;
		this.type = type;
		layoutInflater = (LayoutInflater) activity
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.statuses = new ArrayList<Status>();
		if (statuses != null)
			this.statuses.addAll(statuses);
		try {
			// 保存微博数据
			StorageManager.saveList(statuses, PATH_STORAGE, type);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public int getCount() {
		// 获取微博数,加1为了最后一项显示"更多"
		return statuses.size() + 1;
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

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

	// 获取制定位置的Status对象
	public Status getStatus(int position) {
		if (statuses.size() > 0) {
			return statuses.get(position);
		} else {
			return null;
		}
	}

	// 获取已经显示的微博的最小ID
	public long getMinId() {
		if (statuses.size() > 0)
			return statuses.get(statuses.size() - 1).id;
		else
			return Long.MAX_VALUE;
	}

	// 获取已经显示的微博最大ID
	public long getMaxId() {
		if (statuses.size() > 0)
			return statuses.get(0).id;
		else
			return 0;
	}

	// 添加新的微博
	// 在刷新、显示更多微博时会根据不同的情况决定如何添加微博
	public void putStatuses(List<Status> statuses) {
		if (statuses == null || this.statuses == null)
			return;
		if (statuses.size() == 0)
			return;
		if (this.statuses.size() == 0) {
			this.statuses.addAll(statuses);

		} else if (statuses
				.get(0)
				.getCreatedAt()
				.before(this.statuses.get(this.statuses.size() - 1)
						.getCreatedAt())) {
			this.statuses.addAll(statuses);
			// 添加的statuses比原来的新,并且数量小于等于默认返回数量,直接将statuses添加到前面
		} else if (statuses.get(statuses.size() - 1).getCreatedAt()
				.after(this.statuses.get(0).getCreatedAt())
				&& statuses.size() <= DEFAULT_STATUS_COUNT) {
			this.statuses.addAll(0, statuses);
		} else {
			this.statuses.clear();
			this.statuses.addAll(statuses);
		}
		try {
			// 保存微博信息
			StorageManager.saveList(this.statuses, PATH_STORAGE, type);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 并且刷新ListView
		this.notifyDataSetChanged();
	}

	// 控制View行为的
	private boolean showMoreAnimFlag = false;
	protected boolean showRefreshAnimFlag = false;

	public void showMoreAnim() {
		showMoreAnimFlag = true;
		notifyDataSetChanged();
	}

	public void hideMoreAnim() {
		showMoreAnimFlag = false;
		notifyDataSetChanged();
	}

	public void showRefreshAnim() {
		showMoreAnimFlag = true;
		notifyDataSetChanged();
	}

	public void hideRefreshAnim() {
		showRefreshAnimFlag = false;
		notifyDataSetChanged();
	}

	// 通过url装载要显示的图像,如果图像文件不存在,回通过hideView标志决定是否隐藏ImageView组件
	// hideView: true 隐藏ImageView hideView:false 不做任何动作
	private void loadImage(ImageView imageView, String url, boolean hideView) {
		if (url != null) {
			String imageUrl = WeiboManager.getImageurl(activity, url);
			if (imageUrl != null) {
				imageView.setImageURI(Uri.fromFile(new File(imageUrl)));
				imageView.setVisibility(View.VISIBLE);
				return;
			}
		}
		if (hideView)
			imageView.setVisibility(View.GONE);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = layoutInflater
					.inflate(R.layout.weibo_list_item, null);
		}

		View weiboListItem = convertView.findViewById(R.id.ll_weibo_list_item); // 微博列表项
		View moreWeiboListItem = convertView
				.findViewById(R.id.rl_more_weibo_list_item); // “更多”列表项
		View refreshWeiboListItem = convertView
				.findViewById(R.id.rl_refresh_weibo_list_item); // "刷新"列表项
		refreshWeiboListItem.setVisibility(View.GONE);
		// 当列表项不是最后一项时继续执行
		if (position < statuses.size()) {
			weiboListItem.setVisibility(View.VISIBLE);
			moreWeiboListItem.setVisibility(View.GONE); // “更多”不显示
			Status status = statuses.get(position);

			TextView statusText = (TextView) convertView
					.findViewById(R.id.tv_text);
			TextView name = (TextView) convertView.findViewById(R.id.tv_name);
			TextView createAt = (TextView) convertView
					.findViewById(R.id.tv_created_at);
			ImageView profileImage = (ImageView) convertView
					.findViewById(R.id.iv_profile_image);
			profileImage.setImageResource(R.drawable.portrait); // 设置默认头像
			ImageView picture = (ImageView) convertView
					.findViewById(R.id.iv_picture);
			ImageView statusImage = (ImageView) convertView
					.findViewById(R.id.iv_status_image);
			ImageView verified = (ImageView) convertView
					.findViewById(R.id.iv_verified);

			verified.setVisibility(View.GONE); // 设置认证不可见

			if (status.user != null) {
				// 设置用户认证图标,即各种颜色的“V”或其他符号
				Tools.userVerified(verified, status.user.verified_type);
			}

			statusImage.setImageBitmap(null);
			LinearLayout insideContent = (LinearLayout) convertView
					.findViewById(R.id.ll_inside_content);
			ImageView retweetdetailImage = (ImageView) convertView
					.findViewById(R.id.iv_retweetdetail_image);
			retweetdetailImage.setImageBitmap(null);
			TextView retweetdetailText = (TextView) convertView
					.findViewById(R.id.tv_retweetdetail_text);
			TextView source = (TextView) convertView
					.findViewById(R.id.tv_source);

			// 装载图像
			if (status.user != null) {
				loadImage(profileImage, status.user.profile_image_url, false);
			}
			loadImage(statusImage, status.thumbnail_pic, true);

			statusText.setText(Tools.changeTextToFace(activity,
					Html.fromHtml(Tools.atBlue(status.text))));

			if (status.user != null)
				name.setText(status.user.name); // 显示用户昵称
			// 当前微博有图像
			if (WeiboManager.hasPicture(status))
				picture.setVisibility(View.VISIBLE);
			else
				picture.setVisibility(View.INVISIBLE);

			createAt.setText(Tools.getTimeStr(status.getCreatedAt(), new Date()));
			source.setText("来自: " + status.getTextSource()); // 设置微博来源
			if (status.retweeted_status != null // 如果转发的数据不为空
					&& status.retweeted_status.user != null) {
				insideContent.setVisibility(View.VISIBLE);

				retweetdetailText.setText(Html.fromHtml(Tools.atBlue("@"
						+ status.retweeted_status.user.name + ":"
						+ status.retweeted_status.text)));
				loadImage(retweetdetailImage,
						status.retweeted_status.thumbnail_pic, false);
			} else {
				insideContent.setVisibility(View.GONE);
			}

		} else {
			weiboListItem.setVisibility(View.GONE);
			moreWeiboListItem.setVisibility(View.VISIBLE); // 显示“更多”
			View moreAnim = convertView.findViewById(R.id.pb_more);

			if (showMoreAnimFlag) {
				moreAnim.setVisibility(View.VISIBLE);
			} else {
				moreAnim.setVisibility(View.GONE);
			}
		}
		return convertView;
	}

	@Override
	public void doneProcess(ParentTask task) {
		notifyDataSetChanged(); // 通知更新列表数据
	}
}

关于adapter我们需要关注getView这个方法,因为我们要显示的内容都在这里完成,由于每一条的微博数据比较多,所以童鞋们要注意每一项内容显示到哪个控件上。显示的数据是通过构造方法传进来的,每一条微博数据就是一个Status对象,所以我们需要定义相应的实体类,这个类我们怎么知道怎么定义,这就要知道请求API所返回的内容,

比如:https://api.weibo.com/2/statuses/home_timeline.json。我们请求这个API的时候,返回的字段就是我们需要定义的,如果不太清楚,既要好好看看一下开放平台给我们说明。

可以到这里查看:http://open.weibo.com/wiki/2/statuses/home_timeline

那里很清楚说明了,请求方式,请求参数还有返回的json数据结构。

返回字段说明

返回值字段 字段类型 字段说明
created_at string 微博创建时间
id int64 微博ID
mid int64 微博MID
idstr string 字符串型的微博ID
text string 微博信息内容
source string 微博来源
favorited boolean 是否已收藏,true:是,false:否
truncated boolean 是否被截断,true:是,false:否
in_reply_to_status_id string (暂未支持)回复ID
in_reply_to_user_id string (暂未支持)回复人UID
in_reply_to_screen_name string (暂未支持)回复人昵称
thumbnail_pic string 缩略图片地址,没有时不返回此字段
bmiddle_pic string 中等尺寸图片地址,没有时不返回此字段
original_pic string 原始图片地址,没有时不返回此字段
geo object 地理信息字段 详细
user object 微博作者的用户信息字段 详细
retweeted_status object 被转发的原微博信息字段,当该微博为转发微博时返回 详细
reposts_count int 转发数
comments_count int 评论数
attitudes_count int 表态数
mlevel int 暂未支持
visible object 微博的可见性及指定可见分组信息。该object中type取值,0:普通微博,1:私密微博,3:指定分组微博,4:密友微博;list_id为分组的组号
pic_urls object 微博配图地址。多图时返回多图链接。无配图返回“[]”
ad object array 微博流内的推广微博ID


package com.wwj.sina.weibo.object;

import java.io.Serializable;
import java.util.Date;

import com.wwj.sina.weibo.interfaces.WeiboObject;
import com.wwj.sina.weibo.util.Tools;

import android.text.Html;
/**
 * 微博实体类
 * @author wwj
 *
 */
@SuppressWarnings("serial")
public class Status implements WeiboObject, Serializable {
	/** 字符串型的微博ID */
	public String idstr;
	/** 创建时间 */
	public String created_at;
	/** 微博ID */
	public long id;
	/** 微博信息内容 */
	public String text;
	/** 微博来源(html形式) */
	public String source;

	/** 是否已收藏 */
	public boolean favorited;
	/** 是否被截断 */
	public boolean truncated;
	/** 回复ID */
	public long in_reply_to_status_id;
	/** 回复人UID */
	public long in_reply_to_user_id;
	/** 回复人昵称 */
	public String in_reply_to_screen_name;
	/** 微博MID */
	public long mid;
	/** 中等尺寸图片地址 */
	public String bmiddle_pic;
	/** 原始图片地址 */
	public String original_pic;
	/** 缩略图片地址 */
	public String thumbnail_pic;
	/** 转发数 */
	public int reposts_count;
	/** 评论数 */
	public int comments_count;
	/** 转发的微博内容 */
	public Status retweeted_status;
	/** 微博作者的用户信息字段 */
	public User user; // 不要初始化,否则可能会引起递归创建对象,导致stack溢出

	/** 获取Date形式的创建时间 */
	public Date getCreatedAt() {
		return Tools.strToDate(created_at);
	}

	/** 文本形式的source, */
	private String text_source;

	/** 获取文本形式的source */
	public String getTextSource() {
		if (text_source == null) {
			try {
				// 有时返回的来源是null,可能是一个bug,所以必须加上try...catch...
				text_source = Html.fromHtml(source).toString();
			} catch (Exception e) {
				text_source = source;
			}

		}

		return text_source;

	}
}

我们在授权第三方应用程序访问用户的数据成功后,就会异步获取用户首页微博数据,然后显示到界面上。

package com.wwj.sina.weibo.listener;

import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.weibo.net.DialogError;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;
import com.weibo.net.AsyncWeiboRunner.RequestListener;
import com.wwj.sina.weibo.Home;
import com.wwj.sina.weibo.R;
import com.wwj.sina.weibo.adapters.WeiboListAdapter;
import com.wwj.sina.weibo.interfaces.Const;
import com.wwj.sina.weibo.library.JSONAndObject;
import com.wwj.sina.weibo.library.StorageManager;
import com.wwj.sina.weibo.library.WeiboManager;
import com.wwj.sina.weibo.listener.impl.StatusRequestListenerImpl;
import com.wwj.sina.weibo.object.Status;
import com.wwj.sina.weibo.object.User;
import com.wwj.sina.weibo.util.LogUtils;
import com.wwj.sina.weibo.util.SettingUtil;
import com.wwj.sina.weibo.util.Tools;

public class AuthDialogListener implements WeiboDialogListener, Const {
	private Activity activity;

	public AuthDialogListener(Activity activity) {
		super();
		this.activity = activity;
	}

	// 认证成功后调用
	public void onComplete(Bundle values) {
		// 保存access_token 和 expires_in
		String token = values.getString("access_token");
		String expires_in = values.getString("expires_in");
		SettingUtil.set(activity, SettingUtil.ACCESS_TOKEN, token);
		SettingUtil.set(activity, SettingUtil.EXPIRES_IN, expires_in);
		Toast.makeText(activity, "认证成功", Toast.LENGTH_SHORT).show();

		final Home homeActivity = (Home) activity;
		WeiboListAdapter weiboListAdapter = null;
		// 得到用户的唯一标识
		long uid = Long.parseLong(values.getString("uid"));
		// 保存用户UID
		StorageManager.setValue(activity, "uid", uid);

		WeiboManager.getUserAsync(homeActivity,
				StorageManager.getValue(homeActivity, "uid", 0),
				new RequestListener() {

					@Override
					public void onIOException(IOException e) {
					}

					@Override
					public void onError(WeiboException e) {
					}

					@Override
					public void onComplete(String response) {
						User user = new User();
						JSONAndObject.convertSingleObject((Object) user,
								response);
						Message msg = new Message();
						msg.obj = user;
						homeActivity.handler.sendMessage(msg);
					}
				});

		View homeReloadAnim = homeActivity.findViewById(R.id.pb_home_reload);
		View homeReload = homeActivity.findViewById(R.id.btn_home_reload);
		homeReloadAnim.setVisibility(View.VISIBLE);
		homeReload.setVisibility(View.GONE);

		LinearLayout ll_home_layout = (LinearLayout) homeActivity
				.findViewById(R.id.ll_home_layout);
		List<Status> statuses = WeiboManager.getHomeTimelineAsync(homeActivity,
				new StatusRequestListenerImpl(homeActivity, ll_home_layout,
						HOME));
		weiboListAdapter = new WeiboListAdapter(activity, statuses, Const.HOME);

		homeActivity.homeTimelineAdapter = weiboListAdapter;
		homeActivity.imageWorkQueueMonitor = Tools
				.getGlobalObject(homeActivity).getImageWorkQueueMonitor(
						homeActivity);
		homeActivity.taskWorkQueueMonitor = Tools.getGlobalObject(homeActivity)
				.getTaskWorkQueueMonitor(activity);
		homeActivity.imageWorkQueueMonitor.addDoneAndProcess(Const.HOME,
				weiboListAdapter);
	}

	public void onWeiboException(WeiboException e) {
		LogUtils.e("### onWeiboException");
		// 当认证过程中捕获到WeiboException时调用
		Toast.makeText(activity, "Auth exception:" + e.getMessage(),
				Toast.LENGTH_LONG).show();
		activity.finish();
	}

	public void onError(DialogError e) {
		LogUtils.e("### onError");
		// Oauth2.0认证过程中,当认证对话框中的webView接收数据出现错误时调用此方法
		Toast.makeText(activity, "Auth error:" + e.getMessage(),
				Toast.LENGTH_LONG).show();
		activity.finish();
	}

	public void onCancel() {
		LogUtils.e("### onCancel");
		// Oauth2.0认证过程中,如果认证窗口被关闭或认证取消时调用
		Toast.makeText(activity, "Auth cancel", Toast.LENGTH_LONG).show();
		activity.finish();
	}

}


在认证成功后,回调onComplete方法,就会获取用户个人信息,显示到标题上。下面的代码我解释一下:

statuses的数据是由WeiboManager类当中getHomeTimelineAsync返回来的,这方法传入了一个监听器,StatusRequestListenerImpl这里类实现AsyncWeiboRunner类的RequestListener接口。

LinearLayout ll_home_layout = (LinearLayout) homeActivity
				.findViewById(R.id.ll_home_layout);
		List<Status> statuses = WeiboManager.getHomeTimelineAsync(homeActivity,
				new StatusRequestListenerImpl(homeActivity, ll_home_layout,
						HOME));
		weiboListAdapter = new WeiboListAdapter(activity, statuses, Const.HOME);

		homeActivity.homeTimelineAdapter = weiboListAdapter;
		homeActivity.imageWorkQueueMonitor = Tools
				.getGlobalObject(homeActivity).getImageWorkQueueMonitor(
						homeActivity);
		homeActivity.taskWorkQueueMonitor = Tools.getGlobalObject(homeActivity)
				.getTaskWorkQueueMonitor(activity);
		homeActivity.imageWorkQueueMonitor.addDoneAndProcess(Const.HOME,
				weiboListAdapter);


AsyncWeiboRunner这个就是实现异步请求数据的类,通过构造函数传入进来的listener,调用它的onComplete方法就可以把请求的数据得到。

/*
 * Copyright 2011 Sina.
 *
 * Licensed under the Apache License and Weibo License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.open.weibo.com
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.weibo.net;

import java.io.IOException;

import com.wwj.sina.weibo.util.LogUtils;

import android.content.Context;

/**
 * Encapsulation main Weibo APIs, Include: 1. getRquestToken , 2.
 * getAccessToken, 3. url request. Implements a weibo api as a asynchronized
 * way. Every object used this runner should implement interface
 * RequestListener.
 * 异步请求数据的类
 * @author ZhangJie (zhangjie2@staff.sina.com.cn)
 */
public class AsyncWeiboRunner {

	private Weibo mWeibo;

	public AsyncWeiboRunner(Weibo weibo) {
		this.mWeibo = weibo;
	}

	public void request(final Context context, final String url,
			final WeiboParameters params, final String httpMethod,
			final RequestListener listener) {
		LogUtils.d("### AsyncWeiboRunner request");
		new Thread() {
			@Override
			public void run() {
				try {
					
					String resp = mWeibo.request(context, url, params,
							httpMethod, mWeibo.getAccessToken());

					listener.onComplete(resp);
				} catch (WeiboException e) {
					listener.onError(e);
				}
			}
		}.start();

	}

	// 请求接口
	public static interface RequestListener {

		public void onComplete(String response);

		public void onIOException(IOException e);

		public void onError(WeiboException e);

	}

}


所以真正显示数据的地方在StatusRequestListenerImpl里,通过回调onComplete方法得到的respone,respone就是请求api返回的json数据,我们通过JSONAndObject的convert方法,将json字符串转换为以status作为元素的List。之后就是通过handler发送消息,在界面显示数据了,具体细节你们需要好好看看代码。

package com.wwj.sina.weibo.listener.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.weibo.net.AsyncWeiboRunner.RequestListener;
import com.weibo.net.WeiboException;
import com.wwj.sina.weibo.Home;
import com.wwj.sina.weibo.MessageViewer;
import com.wwj.sina.weibo.R;
import com.wwj.sina.weibo.adapters.WeiboListAdapter;
import com.wwj.sina.weibo.adapters.WeiboListNoMoreAdapter;
import com.wwj.sina.weibo.interfaces.Const;
import com.wwj.sina.weibo.library.JSONAndObject;
import com.wwj.sina.weibo.library.WeiboManager;
import com.wwj.sina.weibo.object.Favorite;
import com.wwj.sina.weibo.object.Status;
import com.wwj.sina.weibo.util.LogUtils;

/**
 * 微博数据请求监听器实现
 * @author wwj
 * 
 */
public class StatusRequestListenerImpl implements RequestListener, Const {

	private WeiboListAdapter weiboListAdapter;
	private WeiboListNoMoreAdapter weiboListNoMoreAdapter; // 隐藏“更多”
	private Activity activity;
	private View parent;
	private int type;

	private Home homeActivity;
	private MessageViewer messageViewer;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日  HH:mm");
			String date = format.format(new Date());
			switch (type) {
			case HOME:
				weiboListAdapter.putStatuses((List<Status>) msg.obj);
				weiboListAdapter.hideMoreAnim();
				weiboListAdapter.hideRefreshAnim();
				homeActivity = (Home) activity;
				if (homeActivity.weiboListView.getAdapter() == null) {
					homeActivity.weiboListView.setAdapter(weiboListAdapter);
					homeActivity.imageWorkQueueMonitor.addDoneAndProcess(HOME,
							weiboListAdapter);
				}
				View homeReloadAnim = parent.findViewById(R.id.pb_home_reload);
				View homeReload = parent.findViewById(R.id.btn_home_reload);
				homeReloadAnim.setVisibility(View.GONE);
				homeReload.setVisibility(View.VISIBLE);

				homeActivity.weiboListView.onRefreshComplete(date);
				break;
			case MESSAGE_AT:
			case USER_TIMELINE:
				weiboListAdapter.putStatuses((List<Status>) msg.obj);
				weiboListAdapter.hideMoreAnim();
				weiboListAdapter.hideRefreshAnim();
				messageViewer = (MessageViewer) activity;
				if (messageViewer.messageListView.getAdapter() == null) {
					messageViewer.messageListView.setAdapter(weiboListAdapter);
					messageViewer.imageWorkQueueMonitor.addDoneAndProcess(type,
							weiboListAdapter);
				}
				View messageReloadAnim = parent
						.findViewById(R.id.pb_message_reload);
				View messageReload = parent
						.findViewById(R.id.btn_message_reload);
				messageReloadAnim.setVisibility(View.GONE);
				messageReload.setVisibility(View.VISIBLE);
				messageViewer.messageListView.onRefreshComplete(date);
				break;
			case MESSAGE_FAVORITE:
				weiboListNoMoreAdapter.putStatuses((List<Status>) msg.obj);
				messageViewer = (MessageViewer) activity;
				if (messageViewer.messageListView.getAdapter() == null) {
					messageViewer.messageListView
							.setAdapter(weiboListNoMoreAdapter);
					messageViewer.imageWorkQueueMonitor.addDoneAndProcess(
							MESSAGE_FAVORITE, weiboListNoMoreAdapter);

				}
				View messageReloadAnim2 = parent
						.findViewById(R.id.pb_message_reload);
				View messageReload2 = parent
						.findViewById(R.id.btn_message_reload);
				messageReloadAnim2.setVisibility(View.GONE);
				messageReload2.setVisibility(View.VISIBLE);
				messageViewer.messageListView.onRefreshComplete(date);

				break;
			default:
				break;
			}
			super.handleMessage(msg);
		};
	};

	public StatusRequestListenerImpl(Activity activity, View parent, int type) {
		this.activity = activity;
		this.parent = parent;
		this.type = type;
	}

	@Override
	public void onComplete(String response) {
		@SuppressWarnings("unchecked")
		List<Status> statuses = JSONAndObject.convert(Status.class, response,
				"statuses");
		switch (type) {
		case HOME:
			LogUtils.d("### home");
			homeActivity = (Home) activity;
			if (homeActivity.homeTimelineAdapter != null) {
				weiboListAdapter = homeActivity.homeTimelineAdapter;
			} else {
				weiboListAdapter = new WeiboListAdapter(homeActivity, null,
						type);
				homeActivity.homeTimelineAdapter = weiboListAdapter;
			}
			break;
		case MESSAGE_AT:
		case USER_TIMELINE:
			LogUtils.d("### MESSAGE_AT");
			messageViewer = (MessageViewer) activity;
			if (messageViewer.messageListAdapter != null) {
				weiboListAdapter = messageViewer.messageListAdapter;
			} else {
				weiboListAdapter = new WeiboListAdapter(messageViewer, null,
						type);
				messageViewer.messageListAdapter = weiboListAdapter;
			}
			break;
		case MESSAGE_FAVORITE:
			LogUtils.d("### MESSAGE_FAVORITE");
			messageViewer = (MessageViewer) activity;
			if (messageViewer.weiboListNoMoreAdapter != null) {
				weiboListNoMoreAdapter = messageViewer.weiboListNoMoreAdapter;
			} else {
				weiboListNoMoreAdapter = new WeiboListNoMoreAdapter(
						messageViewer, null, MESSAGE_FAVORITE);
				messageViewer.messageListAdapter = weiboListNoMoreAdapter;
			}

			List<Favorite> favorites = null;
			favorites = JSONAndObject.convert(Favorite.class, response,
					"favorites");
			statuses = WeiboManager.FavoriteToStatus(favorites);
		default:
			break;
		}
		Message msg = new Message();
		msg.obj = statuses;
		handler.sendMessage(msg);
	}

	@Override
	public void onIOException(IOException e) {
		e.printStackTrace();
	}

	@Override
	public void onError(WeiboException e) {
		e.printStackTrace();
	}

}


这篇博客的关键点应该不在adapter这里,如何异步更新UI才是最重要的,我这里使用的是handler来更新UI。线程的异步操作就主要通过 AsyncWeiboRunner这个类实现,这部分内容就已经囊括了其他微博数据的获取实现流程,获取收藏列表和提到我的微博列表都是类似的实现,我就不多介绍了。


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小巫技术博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值