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

Android 實用編程技巧 12 則:從透明圖片到自訂 Application

編輯:關於 Android 程式設計

日常開發 Android 時,難免會遇到一些「不難但每次都要查」的小需求。以下整理了 12 個實戰中很常派上用場的技巧,涵蓋圖片處理、Intent 跳轉、螢幕亮度、列表過濾、通知、漸層背景與全域資料保存等主題。

1. 產生一張全透明的圖片

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

2. 直接開啟郵件撰寫視窗

用 ACTION_SENDTO 搭配 mailto 協定,系統會自動導向預設的郵件程式,並把收件人帶進去。

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. 以程式控制螢幕亮度

取值的範圍是 0.0 到 1.0,記得是浮點數除法,不然整數除法永遠只會得到 0。

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

4. 過濾特定文字

列表要支援搜尋時,Adapter 本身通常已經實作了 Filterable,直接取用內建的 Filter 即可。

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

5. 監聽 ScrollView 停止滑動

ScrollView 本身沒有滾動監聽,實務上改用 ListView 的 OnScrollListener,在 scrollState 等於 0 時就是「已停止」。

setOnScrollListener(new OnScrollListener() {
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        // TODO
    }
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // TODO
        if (scrollState == 0) Log.i("a", "scrolling stopped...");
    }
});

6. 用系統關聯程式開啟檔案

先把 Bitmap 存成檔案,再用 ACTION_VIEW 加上 MIME 類型交給系統處理。圖片、影片、音訊都可以用同一套寫法,只是 MIME 不同。

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);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File("/sdcard/test.mp4");
intent.setDataAndType(Uri.fromFile(file), "video/*");
startActivity(intent);

提醒:若目標 App 找不到對應的索引處理器,會拋出 ActivityNotFoundException,建議用 try/catch 包起來並提示使用者。

7. 設定文字外觀

程式碼寫法與 XML 寫法二選一,效果相同。

setTextAppearance(context, android.R.style.TextAppearance_Medium);
android:textAppearance="?android:attr/textAppearanceMedium"

8. 指定 Activity 的啟動模式

在 AndroidManifest.xml 宣告,或在送出 Intent 時加上 flag,兩種方式都能達到 singleTop 的效果。

<activity android:name=".ArtistActivity" android:label="Artist" android:launchMode="singleTop">
</activity>
Intent i = new Intent();
i.putExtra(EXTRA_KEY_ARTIST, id);
i.setClass(this, ArtistActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);

9. 做出圓角圖片

核心觀念是「遮罩」:先畫一個圓角矩形當遮罩,再用 PorterDuffXfermode 的 DST_IN 模式,把原圖裁切進這個形狀裡。

Bitmap myCoolBitmap = ...;
int w = myCoolBitmap.getWidth(), h = myCoolBitmap.getHeight();
Bitmap rounder = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(rounder);
Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
xferPaint.setColor(Color.RED);
canvas.drawRoundRect(new RectF(0, 0, w, h), 20.0f, 20.0f, xferPaint);
xferPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(myCoolBitmap, 0, 0, null);
canvas.drawBitmap(rounder, 0, 0, xferPaint);

10. 在通知圖示上顯示未讀數字

Notification notification = new Notification(icon, tickerText, when);
notification.number = 4;

11. 用 shape + style 做漸層背景

先在 drawable/shape.xml 定義漸層,指定起始色、結束色與角度。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient android:startColor="#FFFFFFFF" android:endColor="#FFFF0000" android:angle="270"/>
</shape>

接著在 values/style.xml 建立主題,把背景指向這個 shape。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="NewTheme" parent="android:Theme">
        <item name="android:background">@drawable/shape</item>
    </style>
</resources>

最後在 AndroidManifest.xml 的 application 或個別 activity 上套用主題即可。

<activity android:name=".ShapeDemo" android:theme="@style/NewTheme">

這套寫法同樣能套用在單一控制項上,不必限定於整個視窗。

12. 用自訂 Application 保存全域資料

如果你把資料存在某個 Activity 的 static 欄位裡,當那個 Activity 實例被回收後,下一個實例拿到的就會是 null。比較穩妥的做法是繼承 Application,把狀態放在全域唯一的那一份物件上。

public class MyApplication extends Application {
    private String thing = null;
    public String getThing() { return thing; }
    public void setThing(String thing) { this.thing = thing; }
}

public class MyActivity extends Activity {
    private MyApplication app;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        app = ((MyApplication) getApplication());
        String thing = app.getThing();
    }
}

別忘了在 AndroidManifest.xml 的 <application> 標籤上加上 android:name=".MyApplication",否則系統不會使用你的自訂類別。

以上 12 個小技巧都是實戰中反覆用到的片段,收藏起來能省下不少查文件與除錯的時間。

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