編輯:關於 Android 程式設計
多數 Android 開發都是從原生 API 起步的:一個 Activity、一個 Adapter,功能做完也就差不多了。但當專案開始變複雜,重複勞動越堆越多,你就會認真思考「怎麼寫得更快」。這時候,框架就登場了。本文介紹一個曾經非常流行的選擇:xUtils。
xUtils 主要由四個模組構成。
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
DbUtils db = DbUtils.create(this);
User user = new User(); // User 必須有 id 屬性,或有以 @Id 註解的欄位
user.setEmail("wyouflf@qq.com");
user.setName("wyouflf");
db.saveBindingId(user); // 保存時會回填實體的 id
// 依類型查詢
Parent entity = db.findById(Parent.class, parent.getId());
List<Parent> list = db.findAll(Parent.class);
Parent p1 = db.findFirst(Selector.from(Parent.class).where("name", "=", "test")); // 等於
Parent p2 = db.findFirst(Selector.from(Parent.class).where("name", "=", null)); // IS NULL
Parent p3 = db.findFirst(Selector.from(Parent.class).where("name", "!=", null)); // IS NOT NULL
// WHERE id < 54 AND (age > 20 OR age < 30) ORDER BY id LIMIT ... OFFSET ...
List<Parent> page = db.findAll(Selector.from(Parent.class)
.where("id", "<", 54)
.and(WhereBuilder.b("age", ">", 20).or("age", "<", 30))
.orderBy("id").limit(pageSize).offset(pageSize * pageIndex));
// in / between 的最後一個參數需為陣列或 Iterable
db.findFirst(Selector.from(Parent.class).where("id", "in", new int[]{1, 2, 3}));
db.findFirst(Selector.from(Parent.class).where("id", "between", new String[]{"1", "5"});
// 只取部分欄位、自訂 SQL
db.findDbModelAll(Selector.from(Parent.class).select("name"));
db.findDbModelAll(sql);
db.execNonQuery(sql);
不需要 findViewById,也不需要 setOnClickListener。
@ViewInject(R.id.textView)
TextView textView;
@ResInject(id = R.string.label, type = ResType.String)
private String label;
// 以 id 綁定事件,不受混淆影響,且支援一次綁定多個 id
@Click({R.id.id1, R.id.id2, R.id.id3})
@Click(R.id.test_button)
public void testButtonClick(View v) {
// 方法簽名必須與介面定義一致
}
// Activity 中注入
ViewUtils.inject(this);
// Fragment 中注入
ViewUtils.inject(this, view);
// PreferenceFragment 中注入
ViewUtils.inject(this, getPreferenceScreen());
HttpUtils http = new HttpUtils();
http.send(HttpRequest.HttpMethod.GET, "https://www.lidroid.com",
new RequestCallBack<String>() {
@Override public void onStart() { }
@Override public void onLoading(long total, long current, boolean isUploading) {
testTextView.setText(current + " / " + total);
}
@Override public void onSuccess(ResponseInfo<String> responseInfo) {
textView.setText(responseInfo.result);
}
@Override public void onFailure(HttpException error, String msg) { }
});
RequestParams params = new RequestParams();
params.addHeader(name, value);
params.addQueryStringParameter(name, value);
params.addBodyParameter(name, value); // 純字串參數時使用 BodyParamsEntity
params.addBodyParameter(file, new File(path)); // 加入檔案後改用 MultipartEntity
// 傳送 JSON:params.setBodyEntity(new StringEntity(jsonStr, charset));
HttpUtils http = new HttpUtils();
http.send(HttpRequest.HttpMethod.POST, uploadUrl, params,
new RequestCallBack<String>() {
@Override public void onLoading(long total, long current, boolean isUploading) {
testTextView.setText((isUploading ? "upload: " : "reply: ") + current + " / " + total);
}
@Override public void onSuccess(ResponseInfo<String> responseInfo) {
testTextView.setText("reply: " + responseInfo.result);
}
@Override public void onFailure(HttpException error, String msg) { }
});
HttpUtils http = new HttpUtils();
HttpHandler handler = http.download(
"https://apache.dataguru.cn/httpcomponents/httpclient/source/httpcomponents-client-4.2.5-src.zip",
"/sdcard/httpcomponents-client-4.2.5-src.zip",
true, // 目標檔案已存在時續傳,伺服器不支援 Range 則重新下載
true, // 若回應標頭帶有檔名,下載完成後自動重命名
new RequestCallBack<File>() {
@Override public void onSuccess(ResponseInfo<File> responseInfo) {
testTextView.setText("downloaded: " + responseInfo.result.getPath());
}
@Override public void onFailure(HttpException error, String msg) { }
});
handler.cancel(); // 隨時停止下載
BitmapUtils bitmapUtils = new BitmapUtils(this);
bitmapUtils.display(testImageView, "https://bbs.lidroid.com/static/image/common/logo.png"); // 網路圖
bitmapUtils.display(testImageView, "/sdcard/test.jpg"); // 絕對路徑
bitmapUtils.display(testImageView, "assets/img/wallpaper.jpg"); // assets 目錄
// 長列表滑動時暫停載入,避免錯位
listView.setOnScrollListener(new PauseOnScrollListener(bitmapUtils, false, true));
// 自動產生 TAG,格式為 className.methodName(L:lineNumber)
LogUtils.allowD = false; // 可全域控制各等級是否輸出
LogUtils.customLogger = new MyLogger();
LogUtils.d("wyouflf");
public class xUtilsImageLoader {
private BitmapUtils bitmapUtils;
public xUtilsImageLoader(Context context) {
bitmapUtils = new BitmapUtils(context);
bitmapUtils.configDefaultLoadingImage(R.drawable.logo_new);
bitmapUtils.configDefaultLoadFailedImage(R.drawable.logo_new);
bitmapUtils.configDefaultBitmapConfig(Bitmap.Config.RGB_565);
}
// 自訂回呼:加入淡入效果
public class CustomBitmapLoadCallBack extends DefaultBitmapLoadCallBack<ImageView> {
@Override public void onLoadCompleted(ImageView container, String uri, Bitmap bitmap,
BitmapDisplayConfig config, BitmapLoadFrom from) {
fadeInDisplay(container, bitmap);
}
}
private void fadeInDisplay(ImageView imageView, Bitmap bitmap) {
TransitionDrawable td = new TransitionDrawable(new Drawable[]{
new ColorDrawable(android.R.color.transparent),
new BitmapDrawable(imageView.getResources(), bitmap)});
imageView.setImageDrawable(td);
td.startTransition(500);
}
public void display(ImageView container, String url) {
bitmapUtils.display(container, url, new CustomBitmapLoadCallBack());
}
}
// GET
public void getJson(String url, RequestParams params, final ICallBack cb) {
HttpUtils http = new HttpUtils();
http.configCurrentHttpCacheExpiry(1000 * 10);
http.send(HttpMethod.GET, url, params, new RequestCallBack<String>() {
@Override public void onSuccess(ResponseInfo<String> info) { cb.onResult(info.result); }
@Override public void onFailure(HttpException error, String msg) { }
});
}
// POST 與 GET 幾乎一致,只需替換 HttpMethod
http.send(HttpMethod.POST, url, params, callback);
回過頭看,xUtils 的價值在於把 ORM、視圖注入、網路請求與圖片載入這些反覆手寫的基礎設施一次打包。理解了它的設計思路,即使今天已有更現代的选择,那份「把重複勞動抽象掉」的習慣依然受用。
Android 自訂 TextView 讓圓形紅點隨文字動態移動
在一個有點刁鑽的需求裡:一段文字的右上角需要加上一個圓形紅點,而且右側還擺著一個金額,紅點要隨著文字長度動態移動。為了這個效果,我嘗試各種版面配置組合,結果折騰了一下午還
Android Studio 基本設定整理
Android Studio 的設定看似瑣碎,卻會直接影響日常開發手感。以下整理幾個最常被調整的項目,方便快速建立適合自己的開發環境。進入設定頁面可以從選單進入 Sett
自定義 View 實作鐘擺效果進度條 PendulumView
之前在網路上看到一個 iOS 元件 PendulumView,做出了鐘擺擺動的動畫效果。由於原生進度條的外觀實在算不上好看,於是我思考能否用自定義 View 把這種效果做
CoordinatorLayout 實作入門:滑動刪除與 Behavior 自訂(CoordinatorDemo)
CoordinatorLayout 是 Material Design 元件庫中相當核心的容器,它的價值在於提供了一套「子元件之間互相協調」的機制,讓我們能用宣告式的方式