Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android開發實用Tips彙編

編輯:關於 Android 程式設計

整理一些在Android開發中經常會用到的小知識點。

1. Download文件夾

絕對路徑:

/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());
}

2. ButterKnife綁定多個參數

@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 })

3. submodule的使用方法

submodule可與git保持即時同步。新增:

git submodule add https://github.com/SpikeKing/DroidPlugin.git DroidPlugin

使用:

git submodule update --init --recursive

導入(路徑多於一個時,前面不加冒號):

include ':app', 'DroidPlugin:project:Libraries:DroidPlugin'

引用:

compile project(':DroidPlugin:project:Libraries:DroidPlugin')

4. 更新Github的Fork庫

可參考相關教學,透過配置upstream並pull來同步原始專案的最新變更。

5. 檢測App是否安裝

使用PackageManager:

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;
}

6. Canvas重繪

呼叫 invalidate() 即可觸發重繪。

7. 按鈕的預設點擊效果

波紋效果(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。

8. Proguard去除Log資訊

預設刪除log.i、.v,也可指定刪除.d、.e:

-assumenosideeffects class android.util.Log { *; }
-assumenosideeffects class android.util.Log {
    public static *** d(...);
    public static *** e(...);
}

9. 簡化資料庫的使用

使用資料庫時操作略顯繁瑣,可借助Sugar庫簡化:

compile 'com.github.satyan:sugar:1.3'

10. 點擊被填充連結的EditText

透過在結尾處添加一個不佔位的零寬度空格("\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);
}

OK,以上就是這次的Android開發Tips彙編,希望對你的日常開發有所幫助!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved