編輯:關於 Android 程式設計
本文出自方傑的 Android 新浪微博客戶端系列,:
https://fangjie.sinaapp.com/?p=184
完整專案:
https://github.com/JayFang1993/SinaWeibo
本篇聚焦首頁微博列表:如何設計不規則 Item 的 Adapter、如何在列表底部掛載「加載更多」、如何呈現刷新進度,以及真機上容易忽略的陰影問題。
微博列表的 Item 天生不規則:有的帶轉發的子微博,有的沒有;有的附圖,有的純文字。與其硬用多種 Item 版面配置切換,不如以單一版面搭配 visibility 控制,實作上單純得多。因此這裡選擇繼承 BaseAdapter,自行實作 WeiboAdapter。
package com.fangjie.weibo.ui;
import java.util.List;
import com.fangjie.weibo.R;
import com.fangjie.weibo.bean.Weibo;
import android.content.Context;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class WeiboAdapter extends BaseAdapter {
private Context context;
private List<Weibo> weibos;
public WeiboAdapter(Context context, List<Weibo> weibos) {
this.context = context;
this.weibos = weibos;
}
@Override
public int getCount() {
return weibos.size();
}
@Override
public Object getItem(int position) {
return weibos.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(context, R.layout.wb_item, null);
}
final Weibo weibo = weibos.get(position);
TextView tv_name = (TextView) convertView.findViewById(R.id.txt_wb_item_uname);
TextView tv_content = (TextView) convertView.findViewById(R.id.txt_wb_item_content);
TextView tv_time = (TextView) convertView.findViewById(R.id.txt_wb_item_time);
TextView tv_from = (TextView) convertView.findViewById(R.id.txt_wb_item_from);
TextView tv_comment = (TextView) convertView.findViewById(R.id.txt_wb_item_comment);
TextView tv_repost = (TextView) convertView.findViewById(R.id.txt_wb_item_redirect);
LinearLayout zlayout = (LinearLayout) convertView.findViewById(R.id.lyt_wb_item_sublayout);
TextView tv_zcontent = (TextView) convertView.findViewById(R.id.txt_wb_item_subcontent);
ImageView iv_userhead = (ImageView) convertView.findViewById(R.id.img_wb_item_head);
ImageView iv_isv = (ImageView) convertView.findViewById(R.id.img_wb_item_V);
ImageView iv_content_pic = (ImageView) convertView.findViewById(R.id.img_wb_item_content_pic);
ImageView iv_zcontent_pic = (ImageView) convertView.findViewById(R.id.img_wb_item_content_subpic);
tv_content.setText(weibo.getContent());
tv_name.setText(weibo.getUser().getName());
tv_from.setText("來自:" + Html.fromHtml(weibo.getFrom()));
tv_repost.setText(String.valueOf(weibo.getReposts_count()));
tv_comment.setText(String.valueOf(weibo.getComments_count()));
tv_time.setText(dealTime(weibo.getTime()));
loadBitmap(weibo.getUser().getProfile_image_url(), iv_userhead, 80, 80);
if (!weibo.getBmiddle_pic().equals("")) {
loadBitmap(weibo.getBmiddle_pic(), iv_content_pic, 0, 0);
iv_content_pic.setVisibility(View.VISIBLE);
} else {
iv_content_pic.setVisibility(View.GONE);
}
iv_isv.setVisibility(weibo.getUser().isIsv() ? View.VISIBLE : View.GONE);
if (weibo.getWeibo() != null) {
zlayout.setVisibility(View.VISIBLE);
tv_zcontent.setText("@" + weibo.getWeibo().getUser().getName()
+ ":" + weibo.getWeibo().getContent());
if (!weibo.getWeibo().getBmiddle_pic().equals("")) {
loadBitmap(weibo.getWeibo().getBmiddle_pic(), iv_zcontent_pic, 0, 0);
iv_zcontent_pic.setVisibility(View.VISIBLE);
}
} else {
zlayout.setVisibility(View.GONE);
}
return convertView;
}
public void addItem(Weibo weibo) {
weibos.add(weibo);
}
}
WeiboAdapter 的職責,就是把 List<Weibo> 的資料逐一綁定到每個 View 的子元件上。要注意的是,圖片一律走 loadBitmap() 的非同步載入,避免在 getView() 中做網路 I/O,這部分會在下一篇說明。
Item 的版面配置 wb_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/list_item">
<ImageView android:id="@+id/img_wb_item_head"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginLeft="3dp"
android:layout_marginTop="5dp"
android:src="@drawable/user_head" />
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="vertical">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:id="@+id/txt_wb_item_uname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#424d54"
android:textSize="15dp" />
<ImageView android:id="@+id/img_wb_item_V"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/v"
android:visibility="gone" />
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right">
<TextView android:id="@+id/txt_wb_item_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1小時前"
android:textColor="#efa608"
android:textSize="12dp" />
</RelativeLayout>
</LinearLayout>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="@+id/txt_wb_item_content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#6b717b"
android:textSize="13dp" />
<ImageView android:id="@+id/img_wb_item_content_pic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:visibility="gone" />
</LinearLayout>
<LinearLayout android:id="@+id/lyt_wb_item_sublayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:background="@drawable/popup"
android:orientation="vertical"
android:visibility="gone">
<TextView android:id="@+id/txt_wb_item_subcontent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#6b717b"
android:textSize="13dp" />
<ImageView android:id="@+id/img_wb_item_content_subpic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:visibility="gone" />
</LinearLayout>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:orientation="horizontal">
<TextView android:id="@+id/txt_wb_item_from"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="來自:Touch Android"
android:textColor="#9ba0aa"
android:textSize="12dp" />
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:orientation="horizontal">
<TextView android:id="@+id/txt_wb_item_redirect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/redirect_icon"
android:text="10"
android:textColor="#9ba0aa"
android:textSize="13dp" />
<TextView android:id="@+id/txt_wb_item_comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:drawableLeft="@drawable/comment_icon"
android:text="100"
android:textColor="#9ba0aa"
android:textSize="13dp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
先準備一個簡陋的 load_more.xml,內容就是一個按鈕:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button android:id="@+id/loadMoreButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="加載更多"
android:onClick="loadMore" />
</LinearLayout>
接著在 HomeActivity 中以 addFooterView 把它掛到列表尾端:
View loadMoreView = getLayoutInflater().inflate(R.layout.load_more, null); loadMoreButton = (Button) loadMoreView.findViewById(R.id.loadMoreButton); weibolist.addFooterView(loadMoreView);
小提醒:addFooterView 必須在 setAdapter 之前呼叫,否則在部分版本上會失效。
點擊標題列的刷新鈕時顯示 ProgressBar,任務結束後設為 View.GONE 即可,沒有太多學問,細節可對照原始碼中的 HomeActivity。
列表與上方 TitleBar、TabHost 的交界處,在模擬器上看起來正常,真機上卻會出現一條淡陰影。加上這一行即可消除:
weibolist.setFadingEdgeLength(0);
package com.fangjie.weibo.ui;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fangjie.weibo.R;
import com.fangjie.weibo.bean.Task;
import com.fangjie.weibo.bean.Weibo;
import com.fangjie.weibo.logic.MainService;
import com.fangjie.weibo.util.SharePreferencesUtil;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class HomeActivity extends Activity implements IWeiboAcitivity {
private ListView weibolist;
private List<Weibo> weibos;
private WeiboAdapter adapter;
private TextView tv_title;
private Button btn_refresh;
private Button btn_update;
private LinearLayout progress;
private Button loadMoreButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
init();
}
public void init() {
weibolist = (ListView) findViewById(R.id.lv_weibos);
tv_title = (TextView) findViewById(R.id.txt_wb_title);
btn_refresh = (Button) findViewById(R.id.btn_refresh);
btn_update = (Button) findViewById(R.id.btn_writer);
progress = (LinearLayout) findViewById(R.id.layout_progress);
View loadMoreView = getLayoutInflater().inflate(R.layout.load_more, null);
loadMoreButton = (Button) loadMoreView.findViewById(R.id.loadMoreButton);
weibolist.addFooterView(loadMoreView);
weibolist.setFadingEdgeLength(0);
final String token = SharePreferencesUtil.getLoginUser(HomeActivity.this).getToken();
tv_title.setText(SharePreferencesUtil.getLoginUser(HomeActivity.this).getUserName());
Map<String, Object> params = new HashMap<String, Object>();
params.put("token", token);
progress.setVisibility(View.VISIBLE);
MainService.newTask(new Task(Task.GET_WEIBOS, params));
MainService.addActivty(HomeActivity.this);
loadMoreButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("token", token);
params.put("max_id", weibos.get(weibos.size() - 1).getWid());
loadMoreButton.setText("正在加載,請稍候...");
MainService.newTask(new Task(Task.LOADMORE, params));
MainService.addActivty(HomeActivity.this);
}
});
btn_refresh.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("token", token);
progress.setVisibility(View.VISIBLE);
MainService.newTask(new Task(Task.GET_WEIBOS, params));
MainService.addActivty(HomeActivity.this);
}
});
btn_update.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(HomeActivity.this, "親,工程師還沒寫好呢...", Toast.LENGTH_LONG).show();
}
});
}
@SuppressWarnings("unchecked")
public void refresh(int taskID, Object... objects) {
switch (taskID) {
case Task.GET_WEIBOS:
weibos = (List<Weibo>) objects[0];
adapter = new WeiboAdapter(HomeActivity.this, weibos);
weibolist.setAdapter(adapter);
break;
case Task.LOADMORE:
weibos = (List<Weibo>) objects[0];
for (int i = 1; i < weibos.size(); i++) {
adapter.addItem(weibos.get(i));
}
adapter.notifyDataSetChanged();
loadMoreButton.setText("加載更多");
break;
}
progress.setVisibility(View.GONE);
MainService.reMoveActivty(HomeActivity.this);
}
}
HomeActivity 本身只負責送出任務,實際的網路處理都交給 MainService 這個邏輯層。針對 GET_WEIBOS 與 LOADMORE 兩個任務,MainService 中的對應片段如下:
// 刷新微博
case Task.GET_WEIBOS: {
String token = (String) task.getParams().get("token");
WeiboUtil weiboutil = new WeiboUtil();
List<Weibo> weibos = weiboutil.getWeiboList(token, 0);
msg.obj = weibos;
break;
}
// 加載更多
case Task.LOADMORE: {
String token = (String) task.getParams().get("token");
long max_id = (Long) task.getParams().get("max_id");
WeiboUtil weiboutil = new WeiboUtil();
List<Weibo> weibos = weiboutil.getWeiboList(token, max_id);
msg.obj = weibos;
break;
}
值得學習的架構取捨是:UI 層只發出意圖,把執行細節與回呼集中到單一 Service 中,再由 Handler 把結果送回 Activity 的 refresh() 方法,讓畫面更新與資料取得彻底分離。
Android 快速开发环境搭建(Eclipse 版,附完整资源)
对很多新手来说,自己从零搭建一套开发环境并不轻松;即便是有经验的开发者,折腾环境也常常是件耗时费力的事。不过只要把相关资源都整理到位,快的话半小时到一小时就能搞定。我这篇
AlertDialog 六種對話框用法一次講透
AlertDialog 生成的對話框可劃分為四個區域:圖標區、標題區、內容區、按鈕區。結構如下圖: 掌握它的關鍵,是先理解 Builder 的職責分工,再記住「內容區」
讓 ORMLite 在控制台輸出完整的 SQL 記錄
在 Android 上使用 ORMLite 時,許多人會疑惑:明明 ORM 在背後幫忙拼 SQL,卻只看得到建表語句,insert、select 這些實際操作完全沒有蹤影
Android 繪圖入門:Canvas、Paint 與 Path 三兄弟
Android 的自繪圖功能建立在 View 元件之上,只要覆寫 onDraw(Canvas canvas) 就能作畫。核心只有三個類別: Canvas:依附於某個 V