編輯:關於 Android 程式設計
日常開發 Android 時,難免會遇到一些「不難但每次都要查」的小需求。以下整理了 12 個實戰中很常派上用場的技巧,涵蓋圖片處理、Intent 跳轉、螢幕亮度、列表過濾、通知、漸層背景與全域資料保存等主題。
Bitmap buffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444); buffer.eraseColor(Color.TRANSPARENT);
用 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);
取值的範圍是 0.0 到 1.0,記得是浮點數除法,不然整數除法永遠只會得到 0。
WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.screenBrightness = 100 / 100.0f; getWindow().setAttributes(lp);
列表要支援搜尋時,Adapter 本身通常已經實作了 Filterable,直接取用內建的 Filter 即可。
Filter filter = myAdapter.getFilter(); filter.filter(mySearchText);
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...");
}
});
先把 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 包起來並提示使用者。
程式碼寫法與 XML 寫法二選一,效果相同。
setTextAppearance(context, android.R.style.TextAppearance_Medium);
android:textAppearance="?android:attr/textAppearanceMedium"
在 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);
核心觀念是「遮罩」:先畫一個圓角矩形當遮罩,再用 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);
Notification notification = new Notification(icon, tickerText, when); notification.number = 4;
先在 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">
這套寫法同樣能套用在單一控制項上,不必限定於整個視窗。
如果你把資料存在某個 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 個小技巧都是實戰中反覆用到的片段,收藏起來能省下不少查文件與除錯的時間。
用 RecyclerView 打造真正的下拉刷新與上拉加載
前言 這個需求起因很簡單:專案要用 RecyclerView,想找一個現成的下拉刷新+上拉加載套件,結果翻了一圈沒找到合適的,索然自己動手做了一個。 先說清楚一件事:這裡
Android 學習之路:從非 Java 工程師視角理解系統架構與專案結構
從非 Java 工程師的視角開始 這是「Android 學習之路」系列的第一篇。本文先不急著實作簡易版微信,而是把學習起點、對 Android 的理解,以及 Androi
Android 端透過後端接口取得資料庫資料( Gson 解析實戰)
網上搜了一圈沒找到合適的說明,於是把自己剛學會的這套做法整理出來。核心概念其實很單純:後端提供一份接口文件,Android 端把參數 POST 過去,再把回傳的 JSON
Android 讀取手機聯絡人資訊:電話、信箱、姓名與頭像
「取得聯絡人」幾乎是每個 App 都會碰到的需求——邀請好友、快速分享、客服聯絡等等。由於後續專案很可能還會再用到,乾脆把它包成一個獨立類別,以後直接複製過去就能用。