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

仿新浪微博個人主頁實作:時間格式化與表情文字渲染

編輯:關於 Android 程式設計

本文示範如何打造一個類似新浪微博的個人資訊頁面,並附兩個實用工具類:一個負責把發布時間轉成人類看得懂的相對時間,另一個負責把文字中的表情標記替換成圖片。

資料來源沿用微博開放平台的用戶資訊介面:
https://open.weibo.com/wiki/2/users/show

若前面的基礎功能已經完成,這個頁面寫起來會相當輕鬆,此處不再贅述。

一、時間處理類 DateUtils

把「2016-05-03 00:22:36」這類時間字串,轉成「剛剛」、「5 分鐘前」、「3 天前」這種相對描述。核心邏輯是用現在的時間戳減去目標時間戳,再按不同量級判斷輸出哪種單位。

 /** * 時間處理類 */ public class DateUtils { public String getInterval(String createtime) { //傳入的時間格式必須類似於2012-8-21 17:53:20這樣的格式 String interval = null; SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ParsePosition pos = new ParsePosition(0); Date d1 = sd.parse(createtime, pos); //用現在距離1970年的時間間隔new Date().getTime()減去以前的時間距離1970年的時間間隔d1.getTime()得出的就是以前的時間與現在時間的時間間隔 long time = new Date().getTime() - d1.getTime();// 得出的時間間隔是毫秒 int day = 24 * 3600000; int week = day * 7; if (time / 1000 < 10 && time / 1000 >= 0) { //如果時間間隔小於10秒則顯示“剛剛”time/10得出的時間間隔的單位是秒 interval = "剛剛"; } else if (time / 3600000 < 24 && time / 3600000 > 0) { //如果時間間隔小於24小時則顯示多少小時前 int h = (int) (time / 3600000);//得出的時間間隔的單位是小時 interval = h + "小時前"; } else if (time / 60000 < 60 && time / 60000 > 0) { //如果時間間隔小於60分鐘則顯示多少分鐘前 int m = (int) ((time % 3600000) / 60000);//得出的時間間隔的單位是分鐘 interval = m + "分鐘前"; } else if (time / 1000 < 60 && time / 1000 > 0) { //如果時間間隔小於60秒則顯示多少秒前 int se = (int) ((time % 60000) / 1000); interval = se + "秒前"; } else if (time / day < 7 && time / day > 0) { int d = (int) (time / day); interval = d + "天前"; } else if (time / week < 5 && time / week > 0) { int w = (int) (time / week); interval = w + "周前"; } else { //大於一個月的,則顯示正常的時間,但是不顯示秒 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); ParsePosition pos2 = new ParsePosition(0); Date d2 = (Date) sdf.parse(createtime, pos2); interval = sdf.format(d2); } return interval; } } 

二、表情文字處理類 StringUtils

微博中的表情在資料層其實是「[表情名稱]」這樣的文字。做法是用正則表達式找出所有符合格式的片段,再用 SpannableString 把該段文字替換成對應的圖片。

 public class StringUtils { public static SpannableString getEmotionContent(final Context context, final TextView tv, String source) { SpannableString spannableString = new SpannableString(source); Resources res = context.getResources(); String regexEmotion = "\\[([\u4e00-\u9fa5\\w])+\\]"; Pattern patternEmotion = Pattern.compile(regexEmotion); Matcher matcherEmotion = patternEmotion.matcher(spannableString); Bitmap scaleBitmap; int size = (int) tv.getTextSize(); while (matcherEmotion.find()) { // 獲取匹配到的具體字符 String key = matcherEmotion.group(); // 匹配字符串的開始位置 int start = matcherEmotion.start(); // 利用表情名字獲取到對應的圖片 Integer imgRes = EmotionUtils.getImgByName(key); if (imgRes != null && size > 0) { // 壓縮表情圖片 Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes); if (bitmap != null) { scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true); ImageSpan span = new ImageSpan(context, scaleBitmap); spannableString.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } return spannableString; } } 

這裡有個實作細節值得注意:直接把 mipmap 或 drawable 裡的原圖塞進 TextView 會不成比例,所以程式碼把 TextView 的字級大小當參數傳進來,用 createScaledBitmap 把表情縮到合適尺寸,顯示出來才不會忽大忽小。

三、Manifest 權限與設定

這個應用會用到網路、外部儲存等能力,因此需要事先宣告權限。另外由於頁面會載入多張圖片,容易觸發記憶體不足,這裡透過 largeHeap 申請更大的堆空間。

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="study.sinatest"> <!-- 訪問網絡的權限 --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET"/> <!-- 在SDCard中創建與刪除文件權限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!-- 往SDCard寫入數據權限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application <!-- 此處由於上次多張圖片會使內存溢出,故需申請額外內存 --> android:largeHeap="true" android:allowBackup="true" android:hardwareAccelerated="false" android:icon="@mipmap/weibologo" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".SplashActivity" android:configChanges="keyboardHidden" android:launchMode="singleTask" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity android:name=".LoginActivity"/> <activity android:name=".MainActivity"/> <activity android:name=".HomeActivity"/> <activity android:name=".WriteActivity"/> <activity android:name=".CommentActivity"/> <activity android:name=".MeActivity"/> <activity android:name=".MoreActivity"/> <!-- 授權頁面 --> <activity android:name=".OAuthActivity" android:launchMode="singleTask"> <intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.BROWSABLE"/> <data android:scheme="philn"/> </intent-filter> </activity> <!-- 谷歌服務權限 --> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/> </application> <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true"/> </manifest> 

一點提醒

largeHeap 只是把天花板墊高,並非真正的解法。圖片相關的記憶體問題,更根本的做法是依目標 ImageView 的實際尺寸做降採樣(BitmapFactory.Options 的 inSampleSize),並搭配快取策略;同時記得在 Activity 銷毀時回收不再使用的 Bitmap。另外,targetSdk 較高的版本對上述寫入權限已有更嚴格的分區儲存規範,新專案建議直接採用新的 API。

以上就是這個仿微博個人主頁的完整實作,希望對你的學習有所幫助。

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