編輯:關於 Android 開發
把一些在 Android 開發中反覆用到、卻常常一時想不起來怎麼寫的小知識點整理起來,當成備忘錄隨時翻。

絕對路徑是 /storage/emulated/0/Download/xxx。若要遍歷目錄內容:
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File[] files = file.listFiles();
for (int i = 0; i < files.length; ++i) {
Log.e(TAG, files[i].getAbsolutePath());
}
@OnClick 的參數收的是陣列,多個 id 直接列在同一個註解裡就好,不必一個個寫:
@OnClick({ R.id.dialog_dau_share_wx, R.id.dialog_dau_share_wx_timeline,
R.id.dialog_dau_share_weibo, R.id.dialog_dau_share_qq })
submodule 能讓子專案與主專案保持同步。加入子模組:
git submodule add https://github.com/SpikeKing/DroidPlugin.git DroidPlugin
其他人 clone 後要初始化:
git submodule update --init --recursive
在 settings.gradle 中引入(路徑多於一層時,前面不要加冒號):
include ':app', 'DroidPlugin:project:Libraries:DroidPlugin'
在模組中引用:
compile project(':DroidPlugin:project:Libraries:DroidPlugin')
先把上游設為 remote,再 pull 下來推回自己的 fork,這流程寫過一次就會了,這裡不贅述。
靠 PackageManager 查,抓到資訊就是裝了,抓到 NameNotFoundException 就是沒裝:
private boolean appInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
boolean app_installed;
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
app_installed = true;
} catch (PackageManager.NameNotFoundException e) {
app_installed = false;
}
return app_installed;
}
呼叫 invalidate() 即可觸發重繪,注意它會被節流,別在每一幀裡狂刷。
Android 5.0 以上會有波紋效果,5.0 以下則是陰影變化,用系統屬性就能拿到:
android:background="?android:attr/selectableItemBackground"
也可以繼承系統樣式再覆寫尺寸:
<style name="PersonInfoButton" parent="@android:style/ButtonBar">
<item name="android:layout_width">@dimen/d80dp</item>
<item name="android:layout_height">@dimen/d32dp</item>
<item name="android:textSize">@dimen/d14sp</item>
</style>
注意 parent 要寫成 @android:style/ButtonBar。
預設就會砍掉 Log.i 與 Log.v,若想連 d、e 一起清掉,自行加上規則:
-assumenosideeffects class android.util.Log { *; }
-assumenosideeffects class android.util.Log {
public static *** d(...);
public static *** e(...);
}
SQLiteOpenHelper 那套寫起來相當囉嗦,Sugar ORM 能把 CRUD 縮成一行:
compile 'com.github.satyan:sugar:1.3'
設了 LinkMovementMethod 之後,游標沒辦法移到文字尾端,連結會吃掉點擊。解法是在結尾補一個零寬度空格 \u200B:
private void setEditClickable() {
mEtEditText.setMovementMethod(LinkMovementMethod.getInstance());
Spannable spannable = new SpannableString("https://www.baidu.com");
Linkify.addLinks(spannable, Linkify.WEB_URLS);
// 補上零寬度空格,否則會永遠停在連結上
CharSequence text = TextUtils.concat(spannable, "\u200B");
mEtEditText.setText(text);
}
以上就是這批常用的小抄,之後遇到新的再補上來。
Android 中間人攻擊原理與實作分析
Android 中間人攻擊原理與實作分析 本文介紹Android平台上的中間人攻擊(MITM)思路,並以一個開源專案為例,分析其會話劫持的關鍵技術步驟。 0x00 什麼是
AngularJS 實戰疑難:修正重新整理後 $stateParams 導致的畫面異常
俗話說細節決定成敗,編程更是如此。有些問題平時不出現,卻在特定的操作路徑上突然爆發——重新整理就是最典型的一個。 問題現象 頁面正常載入時,顯示完全正常: 但按下 F
Android 手機衛士:Widget 窗口小部件實作
Android 手機衛士:Widget 窗口小部件實作 AppWidget 可讓使用者在桌面查看應用程式資訊。本範例實作一個顯示行程總數與可用記憶體的小部件,並支援定時更
Android 布局技巧:用 weightSum 與 layout_weight 讓按鈕精準居中並佔據一半寬度
一個屬性組合,解決「居中 + 佔半」的經典需求 本文原創地址:https://www.cnblogs.com/wuyudong/p/5898403.html,轉載請標註來