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

Android 實用小技巧的程式碼大集合

編輯:進階開發

本文彙整多個 Android 開發中經常用到的實用小技巧,涵蓋圖片處理、Intent 呼叫、畫面控制與背景漸層等,方便隨查隨用。

一、讓圖片透明

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

二、直接發送郵件

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

三、程式控制螢幕亮度

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

四、過濾特定文字

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

五、監聽 ScrollView 停止滾動

透過 setOnScrollListener,在 onScrollStateChanged 中判斷 scrollState 為 0 時,即代表滾動停止。

六、以關聯程式開啟檔案

把檔案存成 PNG 後,用 ACTION_VIEW 加上 setDataAndType 指定 MIME 類型即可開啟:

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

影片用 "video/*"、音訊用 "audio/*",同理可開啟對應檔案。

七、設定文字外觀

setTextAppearance(context, android.R.style.TextAppearance_Medium);

八、設定單獨的啟動模式

在 AndroidManifest 中設 android:launchMode="singleTop",程式碼中也可加 intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

九、建立圓角圖片

原理是用遮罩:先畫一個圓角矩形,再用 PorterDuffXfermode 的 DST_IN 模式把原圖「裁」成圓角:

Bitmap rounder = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(rounder);
Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
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);

十、在 Notification 圖示上加數字

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

十一、背景漸層

先建立 drawable/shape.xml:

<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 並在 AndroidManifest 中套用 android:theme="@style/NewTheme" 即可。

十二、保存靜態資料

若在一個實例中保存靜態資料,實例關閉後下一個實例引用時會變成 null。這時必須重寫 Application,用 getter/setter 保存資料,再透過 getApplication() 取得,就能在整個行程中共享。

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