论坛首页 移动开发技术论坛

Android腾讯微博客户端开发五:利用FootView实现ListView滑动动态加载实现分页

浏览 15050 次
精华帖 (0) :: 良好帖 (2) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-07-27   最后修改:2011-07-27
好了,下面开始今天的内容,老规矩,先上图
这张图片左边部分和右边部分还是有很大的不同,不是指内容上,是指布局上,左边的是我今天写这次代码之前的布局,root是用的RelativeLayout,右边是用的FrameLayout,体现在界面上就是右边的list内容可以顶到最上面,而左边的list是在上面的topBar下面。


看布局代码:布局代码还用到了include,主要是用来重用布局的。include一定要放在最下面啊,因为FrameLayout后面的内容会覆盖掉前面的内容,如果你放在上面,将会看不到标题栏。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent">
	<LinearLayout android:orientation="vertical" android:background="#ffffffff" android:layout_width="fill_parent" android:layout_height="fill_parent">
		<ListView android:id="@id/android:list" android:paddingTop="45.0dip" android:paddingBottom="50.0dip" android:layout_width="fill_parent" android:cacheColorHint="#00000000" android:fadingEdge="none" android:fastScrollEnabled="false" android:clipToPadding="false"
			android:layout_height="wrap_content" android:divider="@drawable/list_divider"/>
		<TextView android:text="" android:textSize="20.0sp" android:textColor="#ff5a5a5a" android:gravity="center_horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingTop="15.0dip" android:visibility="invisible"/>
	</LinearLayout>
	<include android:id="@+id/home_top" layout="@layout/top_panel" android:layout_width="fill_parent" android:layout_height="wrap_content" />
</FrameLayout>

把微博列表ListView往下拉,此时还未到加载到数据的最底部。

继续往下拉,ok,见底了,看到更多的提示了嘛,点击它


出现进度条提示

加载完毕之后显示新的一页,继续往下拉,又会看见更多提示,然后如此循环。主要是利用了隐藏。


下面看看主的Activity的代码:

public class HomeTimeLineActivity extends ListActivity implements OnItemClickListener,OnItemLongClickListener{
	
	private DataHelper dataHelper;
	private UserInfo user;
	private MyWeiboSync weibo;
	private ListView listView;
	private HomeAdapter adapter;
	private JSONArray array;
	private AsyncImageLoader asyncImageLoader;
	private Handler handler;
	private ProgressDialog progressDialog;
	private View top_panel;
	private Button top_btn_left;
	private Button top_btn_right;
	private TextView top_title;
	private LinearLayout list_footer;
	private TextView tv_msg;
	private LinearLayout loading;
	private List<JSONObject> list;//微博数据列表
	private ExecutorService executorService;
	private static int PAGE_SIZE = 5;//每页显示的微博条数
	private int TOTAL_PAGE = 0;//当前已经记在的微博页数
	private static int THREADPOOL_SIZE = 5;//线程池的大小
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		setUpViews();
		setUpListeners();
		
		dataHelper = DataBaseContext.getInstance(getApplicationContext());
		weibo = WeiboContext.getInstance();
		
		List<UserInfo> userList = dataHelper.GetUserList(false);
		
		SharedPreferences preferences = getSharedPreferences("default_user",Activity.MODE_PRIVATE);
		String nick = preferences.getString("user_default_nick", "");//取得默认账号信息
		
		if (nick != "") {
			user = dataHelper.getUserByName(nick,userList);
			top_title.setText(nick);//顶部工具栏昵称
		}
		
		weibo.setAccessTokenKey(user.getToken());
		weibo.setAccessTokenSecrect(user.getTokenSecret());
		
		progressDialog = new ProgressDialog(HomeTimeLineActivity.this);// 生成一个进度条
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setTitle("请稍等");
		progressDialog.setMessage("正在读取数据中!");
		handler = new GetHomeTimeLineHandler();
		
		executorService.submit(new GetHomeTimeLineThread());//耗时操作,开启一个新线程获取数据
		progressDialog.show();
	}
	
	private void setUpViews(){
		list_footer = (LinearLayout)LayoutInflater.from(HomeTimeLineActivity.this).inflate(R.layout.list_footer, null);
		tv_msg = (TextView)list_footer.findViewById(R.id.tv_msg);
		loading = (LinearLayout)list_footer.findViewById(R.id.loading);
		listView = getListView();
		top_panel = (View)findViewById(R.id.home_top);
		top_btn_left = (Button)top_panel.findViewById(R.id.top_btn_left);
		top_btn_right = (Button)top_panel.findViewById(R.id.top_btn_right);
		top_title = (TextView)top_panel.findViewById(R.id.top_title);
		listView.addFooterView(list_footer);//这儿是关键中的关键呀,利用FooterVIew分页动态加载
		list = new ArrayList<JSONObject>();
		executorService = Executors.newFixedThreadPool(THREADPOOL_SIZE);
	}
	
	private void setUpListeners(){
		listView.setOnItemClickListener(this);
		listView.setOnItemLongClickListener(this);
		top_btn_right.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(HomeTimeLineActivity.this,AddWeiboActivity.class);
				startActivity(intent);
			}
		});
		tv_msg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Toast.makeText(HomeTimeLineActivity.this, "我将消失了", Toast.LENGTH_SHORT).show();
				executorService.submit(new GetHomeTimeLineThread());
				tv_msg.setVisibility(View.GONE);//隐藏更多提示的TextView
				loading.setVisibility(View.VISIBLE);//显示最下方的进度条
			}
		});
	}
	
	class GetHomeTimeLineHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			adapter = new HomeAdapter(HomeTimeLineActivity.this, list);
			listView.setAdapter(adapter);
			listView.setSelection((TOTAL_PAGE-1)*PAGE_SIZE+1);//设置最新获取一页数据成功后显示数据的起始数据
			progressDialog.dismiss();// 关闭进度条
			loading.setVisibility(View.GONE);//隐藏下方的进度条
			tv_msg.setVisibility(View.VISIBLE);//显示出更多提示TextView
		}
	}
	
	class GetHomeTimeLineThread extends Thread {
		@Override
		public void run() {
			refreshList();
			Message msg = handler.obtainMessage();//通知线程来处理范围的数据
			handler.sendMessage(msg);
		}
	}
	
	private void refreshList(){
		String jsonStr = weibo.getHomeMsg(weibo.getAccessTokenKey(), weibo.getAccessTokenSecrect(), PageFlag.PageFlag_First, (TOTAL_PAGE+1)*PAGE_SIZE);
		try {
			JSONObject dataObj = new JSONObject(jsonStr).getJSONObject("data");
			array = dataObj.getJSONArray("info");
			if(array!=null&&array.length()>0){
				TOTAL_PAGE++;
				list.clear();
				int lenth =array.length();
				for(int i = 0;i<lenth;i++){
					list.add(array.optJSONObject(i));
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	
	class HomeAdapter extends BaseAdapter {
		private Context context;
		private LayoutInflater inflater;
		private List<JSONObject> list;
		
		public HomeAdapter(Context context, List<JSONObject> list) {
			super();
			this.context = context;
			this.list = list;
			this.inflater = LayoutInflater.from(context);
		}

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

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

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

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			asyncImageLoader = new AsyncImageLoader();
			HomeViewHolder viewHolder = new HomeViewHolder();
			JSONObject data = (JSONObject)list.get(position);
			JSONObject source = null;
			convertView = inflater.inflate(R.layout.home_list_item, null);
			try {
				source = data.getJSONObject("source");
			} catch (JSONException e1) {
				e1.printStackTrace(); 
			}
			viewHolder.home_headicon = (ImageView) convertView.findViewById(R.id.home_headicon);
			viewHolder.home_nick = (TextView) convertView.findViewById(R.id.home_nick);
			viewHolder.home_hasimage = (ImageView) convertView.findViewById(R.id.home_hasimage);
			viewHolder.home_timestamp = (TextView) convertView.findViewById(R.id.home_timestamp);
			viewHolder.home_origtext = (TextView) convertView.findViewById(R.id.home_origtext);
			viewHolder.home_source = (TextView) convertView.findViewById(R.id.home_source);
			
			if(data!=null){
				try {
					convertView.setTag(data.get("id"));
					//viewHolder.home_headicon.setImageDrawable(ImageUtil.getDrawableFromUrl(data.getString("head")+"/100"));//同步加载图片
					viewHolder.home_nick.setText(data.getString("nick"));
					viewHolder.home_timestamp.setText(TimeUtil.converTime(Long.parseLong(data.getString("timestamp"))));
					//viewHolder.home_origtext.setText(data.getString("origtext"), TextView.BufferType.SPANNABLE);
					
					/*Spannable spannable = (Spannable)viewHolder.home_origtext.getText();//加高亮显示
					spannable.setSpan(new BackgroundColorSpan(Color.RED), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);*/
					
					SpannableString spannable = new SpannableString(data.getString("origtext"));
					//把字符串解析成本地表情
					spannable = TextUtil.getImageSpannableString(spannable, RegexUtil.getStartAndEndIndex(data.getString("origtext"), Pattern.compile("\\/[\u4e00-\u9fa5a-zA-Z]{1,3}")), getResources());
					viewHolder.home_origtext.setText(spannable);
					
					
					if(source!=null){
						viewHolder.home_source.setText(source.getString("nick")+":"+source.getString("origtext"));
						viewHolder.home_source.setBackgroundResource(R.drawable.home_source_bg);
					}
					//异步加载图片
					Drawable cachedImage = asyncImageLoader.loadDrawable(data.getString("head")+"/100",viewHolder.home_headicon, new ImageCallback(){
	                    @Override
	                    public void imageLoaded(Drawable imageDrawable,ImageView imageView, String imageUrl) {
	                        imageView.setImageDrawable(imageDrawable);
	                    }
	                });
					if (cachedImage == null) {
						viewHolder.home_headicon.setImageResource(R.drawable.icon);
					} else {
						viewHolder.home_headicon.setImageDrawable(cachedImage);
					}
					if(data.getJSONArray("image")!=null){
						viewHolder.home_hasimage.setImageResource(R.drawable.hasimage);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return convertView;
		}
	}
	
	static class HomeViewHolder {
		private ImageView home_headicon;
		private TextView home_nick;
		private TextView home_timestamp;
		private TextView home_origtext;
		private TextView home_source;
		private ImageView home_hasimage;
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
		CharSequence [] items = null;
		try {
			items= new CharSequence[]{"转播","对话","点评","收藏",((JSONObject)array.opt(position)).getString("nick"),"取消"};
		} catch (JSONException e) {
			e.printStackTrace();
		}
		new AlertDialog.Builder(HomeTimeLineActivity.this).setTitle("选项").setItems(items,new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0: {
						}
							break;
						case 1: {
						}
							break;
						case 2: {
						}
							break;
						case 3: {
						}
							break;
						case 4: {
						}
							break;
						case 5: {
						}
							break;
						default:
							break;
						}
			}
		}).show();
		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		JSONObject weiboInfo = (JSONObject)array.opt(position);
		Intent intent = new Intent(HomeTimeLineActivity.this, WeiboDetailActivity.class);
		try {
			intent.putExtra("weiboid", weiboInfo.getString("id"));
			startActivity(intent);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		super.onCreateOptionsMenu(menu);
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.home_timeline_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings: {

		}
			break;
		case R.id.menu_official: {

		}
			break;
		case R.id.menu_feedback: {

		}
			break;
		case R.id.menu_account: {
			Intent intent = new Intent(HomeTimeLineActivity.this,
					AccountActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.menu_about: {
			Intent intent = new Intent(HomeTimeLineActivity.this,
					AddWeiboActivity.class);
			startActivity(intent);
		}
			break;
		case R.id.menu_quit: {

		}
			break;
		default:
			break;
		}
		return true;
	}
}


下面的布局文件是你所看见的更多提示和下方的进度条布局文件:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:minHeight="?android:listPreferredItemHeight"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView android:textSize="16.0sp" android:textColor="#ff545454" android:gravity="center" android:id="@id/tv_msg" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="更多"/>
    <LinearLayout android:gravity="center" android:layout_gravity="center" android:orientation="horizontal" android:id="@id/loading" android:layout_width="fill_parent" android:layout_height="fill_parent">
        <ProgressBar android:layout_gravity="center_vertical" android:id="@id/footprogress" android:layout_width="wrap_content" android:layout_height="wrap_content" android:indeterminateBehavior="repeat" style="?android:progressBarStyleSmallInverse" />
        <TextView android:textColor="#ff000000" android:gravity="left|center" android:padding="3.0px" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="读取中" />
    </LinearLayout>
</LinearLayout>



最后有一个问题就是 就是腾讯API首页时间线没有提供和分页相关的参数,什么意思啊,举个例子:就是说点击更多之前你加载的是0-10条数据,假设一页大小是10条数据,点击更多之后,就会多10条,但是API调用时是请求的0-20条(关于这个没有什么可争辩的,你们自己试一试就知道了),故中间代码有一处我把list clear了一下,要不然要出错。这肯能是与首页时间线的数据更新速度很快有关,但不管怎么说,分页我们已经实现了,以后的所有页面都会用到这个footView分页的技术,是不是很爽,比下一页,上一页,是不是爽多了?
  • 大小: 245.8 KB
  • 大小: 139.7 KB
  • 大小: 112.8 KB
  • 大小: 122.9 KB
  • 大小: 141.3 KB
   发表时间:2011-07-27   最后修改:2011-07-27
话说我收听的这个赵薇好像是个冒牌货,不过她的微博还是值得收听滴的,内容不错。好了,快两点俩哦,我睡觉了,明天还要坐车回成都。嘎嘎,今天够悲剧呀,本来12点就差不多能弄完得。
0 请登录后投票
   发表时间:2011-07-27  
So wonderful!
0 请登录后投票
   发表时间:2011-07-27  
等车,无聊啊
0 请登录后投票
   发表时间:2011-07-27  
不错,不错
0 请登录后投票
   发表时间:2011-07-27  
利用footView实现的分页技术很简单嘛,不知楼主的有什么高明之处?
0 请登录后投票
   发表时间:2011-07-27  
gundumw100 写道
利用footView实现的分页技术很简单嘛,不知楼主的有什么高明之处?

对,做过的会认为很简单,给不知道的人分享一下吧。
0 请登录后投票
   发表时间:2011-07-28  
其实我是来看微博的。。
0 请登录后投票
   发表时间:2011-07-28  
其实我是来看楼主头像的,哈哈
0 请登录后投票
   发表时间:2011-07-28  
喜欢楼主的头像。。。哈哈
0 请登录后投票
论坛首页 移动开发技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics