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

老规矩,先上图
这张图片左边部分和右边部分还是有很大的不同,不是指内容上,是指布局上,左边的是我今天写这次代码之前的布局,root是用的RelativeLayout,右边是用的FrameLayout,体现在界面上就是右边的list内容可以顶到最上面,而左边的list是在上面的topBar下面。
Android腾讯微博客户端开发5:利用FootView实现ListView滑动动态加载实现分页_第1张图片

看布局代码:布局代码还用到了include,主要是用来重用布局的。
<?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>

把图片往下拉,此时还未到加载到数据的最底部。
Android腾讯微博客户端开发5:利用FootView实现ListView滑动动态加载实现分页_第2张图片
继续往下拉,ok,见底了,看到更多的提示了嘛,点击他
Android腾讯微博客户端开发5:利用FootView实现ListView滑动动态加载实现分页_第3张图片

出现进度条提示
Android腾讯微博客户端开发5:利用FootView实现ListView滑动动态加载实现分页_第4张图片
加载完毕之后显示新的一页,继续往下拉,又会看见更多提示,然后如此循环。主要是利用了隐藏。
Android腾讯微博客户端开发5:利用FootView实现ListView滑动动态加载实现分页_第5张图片

下面看看主的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>

你可能感兴趣的:(android,ListView,分页,footview,滑动加载)