Android開發之那些好用的資料結構與API(三)

YungFan發表於2017-12-13

之前的系列文章 Android開發之那些好用的資料結構與APIAndroid開發之那些好用的資料結構與API(二)中,已經介紹了一些,趁熱打鐵,本次介紹的內容很實用哦~~

1、RoundedBitmapDrawable

RoundedBitmapDrawable 是 android.support.v4.graphics.drawable 裡面的一個類,但是記得一定得是21+以上的版本。它是用來建立簡單的圓角圖片,以前做App時,個人中心經常有個圓角的個人頭像,可能大家都會用第三方的庫來做,其實在2014年的Google IO大會後Google釋出了新的Support lib,其中就有這個類和相應的API,看看最新的Android系統中聯絡人的圓形頭像,就是基於此而做的,API很簡單,如下:

ImageView imageView = (ImageView) findViewById(R.id.img);
Resources res = getResources();
// 獲取Bitmap圖片
Bitmap src = BitmapFactory.decodeResource(res, R.drawable.pic);
// 建立RoundedBitmapDrawable物件
RoundedBitmapDrawable dr = RoundedBitmapDrawableFactory
.create(res, src);
// 設定圓角半徑
dr.setCornerRadius(Math.max(src.getWidth(), src.getHeight()) / 2.0f);
// 顯示圓角圖片
imageView.setImageDrawable(dr); 
複製程式碼

原圖與效果圖:

原圖.png
RoundedBitmapDrawable.png

2、DateUtils

在Android中經常要處理與日期有關的欄位,當然可以用Java中的日期處理API,但是Android中也提供了,在android.text.format.DateUtils 類中有如下幾個方法,下面以幾個簡單的案例進行介紹。

(1)格式化時間,比Java自帶的要爽得多,麻麻說再也不需要記憶亂七八糟的 yyyy年MM月dd日了

//格式化時間,最後引數設定顯示的格式
String date = DateUtils.formatDateTime(MainActivity.this,
System.currentTimeMillis(), DateUtils.FORMAT_SHOW_DATE
						| DateUtils.FORMAT_SHOW_TIME
						| DateUtils.FORMAT_SHOW_YEAR
						| DateUtils.FORMAT_ABBREV_MONTH 
                        | DateUtils.FORMAT_SHOW_WEEKDAY);
tv.setText(date);
複製程式碼

formatDateTime.png

(2)  返回相對於當前時間的最大區間表示的字串:幾(分鐘,小時,天,周,月,年)前/後。想想微博上那些時間,是不是瞬間覺得簡單了~~

CharSequence date = DateUtils.getRelativeTimeSpanString(System
				.currentTimeMillis() + 1000*1000);

tv.setText(date);
複製程式碼

getRelativeTimeSpanString1.png

(3)  返回相對於當前時間的一個時間字串:在同一天顯示時分;在不同一天,顯示月日;在不同一年,顯示年月日

CharSequence date = DateUtils.getRelativeTimeSpanString(
MainActivity.this, System.currentTimeMillis() + 10000 * 10000);

tv.setText(date);
複製程式碼

getRelativeTimeSpanString2.png

(4)返回兩個時間值間的相距字串

String date = DateUtils.formatDateRange(MainActivity.this,
				System.currentTimeMillis(),
				System.currentTimeMillis() + 60 * 60 * 10000,
				DateUtils.FORMAT_SHOW_TIME); 

tv.setText(date);
複製程式碼

formatDateRange.png

以上就是本次要介紹的內容,內容雖然不是很多,但是很實用,正所謂內容不在多而在精,大家可以在專案中試試看~~

相關文章