Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android 實用小技巧的程式碼片段整理

編輯:初階開發

以下幾段都是開發中反覆會用到的小片段,直接收藏即可。

1. 讓圖片變全透明

Bitmap buffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
buffer.eraseColor(Color.TRANSPARENT);

2. 直接發送郵件

Intent intent = new Intent(Intent.ACTION_SENDTO,
        Uri.fromParts("mailto", "test@test.com", null));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

3. 程式控制螢幕亮度

WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 100 / 100.0f;
getWindow().setAttributes(lp);

screenBrightness 取 0.0f 到 1.0f,設為負值則沿用系統自動亮度。

4. 過濾特定文字

Filter filter = myAdapter.getFilter();
filter.filter(mySearchText);

5. 監聽 ScrollView 停止滾動

setOnScrollListener(new OnScrollListener() {
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        // 可在此處理滾動過程
    }

    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == 0) {
            Log.i("a", "scrolling stopped...");
        }
    }
});

6. 存檔後以關聯程式開啟

Bitmap bmp = getImageBitmap(jpg);
String path = getFilesDir().getAbsolutePath() + "/test.png";
File file = new File(path);
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(CompressFormat.PNG, 100, fos);
fos.close();

Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(path)), "image/png");
startActivity(intent);

實務提醒:以 ACTION_VIEW 開啟檔案時,若目標機型為 Android 7.0 以上,直接傳 file:// URI 會觸發 FileUriExposedException,需改用 FileProvider 產生 content:// URI 並於 Intent 中加上 FLAG_GRANT_READ_URI_PERMISSION。

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