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

Android 開發實用技巧彙編:Application、ListView 排序、浮點數格式化、占位符與動態載入圖片

編輯:關於 Android 程式設計

一、Application 的用途

1. Application 基本概念

建立時機:Application 在啟動時會呼叫其無參數的建構方法來建立實例。

建構方法:Application 的無參數建構方法必須宣告為 public,否則運行時將會報錯。

單例特性:在一個應用中,Application 是單例的。

核心用途:所有元件共享同一個 Application,可作為資料共享、傳遞與快取的中樞。

常見應用場景包括:

a. 元件間資料傳遞:當元件之間需要傳遞的資料量較大時,盡量不要依賴 Intent 的附加域,而是將資料寄放在 Application 中,讓它充當中轉站;

b. 網路資料快取:從網路下載的資料可暫時快取到 Application 中,若資料量過大則可考慮改存至 SD 卡;

c. 注意記憶體洩漏:由於 Application 是靜態且長生命周期的,存放資料時務必留意生命週期,避免造成記憶體洩漏。

2. 自訂 Application 技巧

實務中經常需要自訂一個 MyApplication,將其設為單例,並在 AndroidManifest.xml 中註冊。做法如下:

(1) 將 MyApplication 設為單例

a. 定義一個私有、靜態的 MyApplication;

b. 提供一個公開的靜態方法,將 this 賦值給自訂的 MyApplication 物件;

c. 提供一個公開、靜態的方法以取得該物件。

public class MyApplication extends Application {
     /* 單例模式:私有靜態的本類物件 */
     private static MyApplication mApplication;

     /* 單例模式:建構方法,注意 Application 的建構方法必須是 public 的 */
     public MyApplication() {
         mApplication = this;
     }

     /* 單例模式:公開靜態的取得方法 */
     public static MyApplication getInstance() {
         return mApplication;
     }
 }

如此一來,便能透過 getInstance() 方法在任意類別中存取 Application,並讀取其中的資料。

(2) 在 AndroidManifest.xml 中註冊自訂的 Application

於 manifest 節點中透過 android:name 屬性指向自訂的 MyApplication 即可。

(3) 取得 Application 的方法

呼叫系統方法:在 Activity 中可呼叫 getApplicationContext() 取得 Application。

透過自訂方法:如上所述,可呼叫自訂的 getInstance() 方法取得實例。

二、ListView 中元素的排序

ListView 的排序本質上就是對資料來源進行排序。給集合排序可使用 Collections 的 sort(list, Comparator) 方法,它需要兩個參數:第一個是待排序的集合,第二個是比较器。

比較器需自行建立並重寫其中的 compare() 方法,該方法回傳 1 或 -1,用以控制升序或降序:

 Collections.sort(mList, new Comparator<Integer>() {
     @Override
     public int compare(Integer a, Integer b) {
         if (a > b) {
             return 1;
         }
         return -1;
     }
 });

如此一來,mList 集合便會自動完成排序。

三、格式化浮點數

在程式中保留 float 或 double 的小數位數,有以下幾種常見做法。

1. 使用 DecimalFormat 格式化浮點數

DecimalFormat 類可以依據一定的格式來格式化浮點數。常見的格式化字元是 "#" 與 "0"。建立時將格式樣式傳入,例如要保留兩位小數就傳入 "#.00",以此類推。呼叫 format 方法並傳入待格式化的浮點數,回傳結果即為固定位數的數字字串。

值得注意的是,這種方法回傳的是字串形式;若後續還需要拿這個數字進行計算,就應改用 BigDecimal。

精度問題:DecimalFormat 採用的是 half-even 捨入法,這並非一般認知的四捨五入。當遇到 5 時,會向最近的偶數靠攏。

例如:

 System.out.println(new java.text.DecimalFormat("0.00").format(3.135)); // 5 最近的偶數是 4,輸出 3.14
 System.out.println(new java.text.DecimalFormat("0.00").format(3.125)); // 5 最近的偶數是 2,輸出 3.12
 float pi = 3.1415926f;
 DecimalFormat decimalFormat = new DecimalFormat("#.00");
 String formatData = decimalFormat.format(pi);
 System.out.println(formatData);

2. 利用 BigDecimal 實現

建立 BigDecimal 物件時傳入待格式化的浮點數,接著呼叫 setScale 方法,傳入需保留的小數位數與 BigDecimal.ROUND_HALF_UP 常量,最後轉回浮點數即可。

 float pi = 3.1415926f;
 BigDecimal bigDecimal = new BigDecimal(pi);
 float result = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
 System.out.println(result);

與浮點數有關的建構方法:BigDecimal 的建構方法可傳入浮點數或字串,但使用浮點數建構並不精確,結果會多出意料之外的位數,因此建議盡量使用字串建構。例如:

 BigDecimal bd1 = new BigDecimal(0.05);
 System.out.println(bd1.toString());
 BigDecimal bd2 = new BigDecimal("0.05");
 System.out.println(bd2.toString());

輸出結果分別為:

 0.05000000000000000277555756156289135105907917022705078125
 0.05

由此可見,使用字串建構能獲得更高的精確度。BigDecimal 的基本運算方法包括:加法 add、減法 subtract、乘法 multiply、除法 divide,以及 setScale 四捨五入。

 // 加法
 BigDecimal bd3 = new BigDecimal(String.valueOf(0.05));
 BigDecimal bd4 = new BigDecimal(String.valueOf(0.01));
 System.out.println((bd3.add(bd4)).doubleValue());

 // 減法
 BigDecimal bd5 = new BigDecimal(String.valueOf(0.05));
 BigDecimal bd6 = new BigDecimal(String.valueOf(0.01));
 System.out.println((bd5.subtract(bd6)).doubleValue());

 // 乘法
 BigDecimal bd7 = new BigDecimal(String.valueOf(0.05));
 BigDecimal bd8 = new BigDecimal(String.valueOf(0.01));
 System.out.println((bd7.multiply(bd8)).doubleValue());

 // 除法(此處未考慮資料錯誤的情況)
 int scale = 10;
 BigDecimal bd9 = new BigDecimal(String.valueOf(0.05));
 BigDecimal bd10 = new BigDecimal(String.valueOf(0.03));
 System.out.println((bd9.divide(bd10, scale, BigDecimal.ROUND_HALF_EVEN)).doubleValue());

 // 四捨五入
 scale = 4;
 BigDecimal bd11 = new BigDecimal(String.valueOf(3.1415926));
 System.out.println(bd11.setScale(scale, BigDecimal.ROUND_HALF_UP).toString());

捨入模式說明:

ROUND_CEILING:向正無窮方向捨入;ROUND_DOWN:向零方向捨入;ROUND_FLOOR:向負無窮方向捨入;ROUND_HALF_DOWN:向距離近的一方捨入,兩邊相等時向下捨入(如 2.155 保留兩位為 2.15);ROUND_HALF_UP:向距離近的一方捨入,兩邊相等時向上捨入(如 2.155 保留兩位為 2.16),即一般認知的四捨五入;ROUND_HALF_EVEN:向距離近的一方捨入,兩邊相等時若保留位為奇數則用 ROUND_HALF_UP,為偶數則用 ROUND_HALF_DOWN;ROUND_UNNECESSARY:精確計算,不需捨入;ROUND_UP:向遠離 0 的方向捨入。

四、string.xml 占位符

開發中經常會遇到需要在 string.xml 中使用占位符的情況:

 <string name="delete_success">刪除<xliff:g id="name">%1$s</xliff:g>成功</string>
 <string name="upload_success">%1$s上傳到%2$s成功</string>

1. xliff:g 標籤

參考資料:

https://blog.csdn.net/hustpzb/article/details/6870817

https://blog.csdn.net/ganggang1st/article/details/6804086

五、動態引用圖片

假設資源檔中存放了 image_1.png、image_2.png、image_3.png 三張圖片,需要依傳入參數動態引用對應的圖片,共有三種解法。

需要特別提醒:直接以 R.drawable.xx 動態引用是行不通的,因為每個這類 id 都對應 R 檔中的一個固定 id,若無對應的 id,編譯便無法通過。

方案一:圖片位於 drawable 目錄下的情況

 Resources resources = this.getResources();
 int imageIndentify = resources.getIdentifier(imageName, "drawable", "chao.yun.demo");

透過上述程式碼即可拼接圖片名稱,依傳入參數動態取得圖片對應的 id。getIdentifier 方法回傳的是圖片對應的 id:第一個參數是圖片名稱,找不到時回傳 0;第二個參數是資源類型,圖片即為 "drawable"(注意這不是具體目錄,因此無需註明 "drawable-hdpi");第三個參數是建立專案時的總 package 名稱,與 manifest 設定檔中的包名相同。

layout 佈局程式碼:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical" >
     <LinearLayout
         android:id="@+id/ll_1"
         android:layout_width="fill_parent"
         android:layout_height="0px"
         android:layout_weight="1"></LinearLayout>
     <LinearLayout
         android:id="@+id/ll_2"
         android:layout_width="fill_parent"
         android:layout_height="0px"
         android:layout_weight="1"></LinearLayout>
     <LinearLayout
         android:id="@+id/ll_3"
         android:layout_width="fill_parent"
         android:layout_height="0px"
         android:layout_weight="1"></LinearLayout>
 </LinearLayout>

Activity 程式碼:

 public class MainActivity extends Activity {
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         LinearLayout ll_1 = (LinearLayout) findViewById(R.id.ll_1);
         LinearLayout ll_2 = (LinearLayout) findViewById(R.id.ll_2);
         LinearLayout ll_3 = (LinearLayout) findViewById(R.id.ll_3);
         Resources resources = this.getResources();
         String imageName = "image_" + 1;
         int imageIndentify = resources.getIdentifier(imageName, "drawable", "chao.yun.demo");
         ll_1.setBackgroundResource(imageIndentify);
         imageName = "image_" + 2;
         imageIndentify = resources.getIdentifier(imageName, "drawable", "chao.yun.demo");
         ll_2.setBackgroundResource(imageIndentify);
         imageName = "image_" + 3;
         imageIndentify = resources.getIdentifier(imageName, "drawable", "chao.yun.demo");
         ll_3.setBackgroundResource(imageIndentify);
     }
 }

效果圖:

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