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

Android 開發技巧:像 QQ 一樣在輸入框中混排文字與表情圖像

編輯:Android 開發實例

和 TextView 一樣,EditText 也能進行圖文混排。差別在於 TextView 只用來顯示圖文混排效果,而 EditText 不僅能顯示,還能混合輸入文字與圖像。先回想一下 QQ 聊天輸入框——裡頭可以同時輸入文字和表情圖像。這種效果在 Android SDK 中其實只需幾行程式碼就能實現。先來欣賞一下即將完成的效果。


圖5.16 在EditText控件中輸入文字和圖像

為了實作這個程式,先準備素材,也就是要在 EditText 中輸入的圖片檔。本例準備了 9 個 png 圖檔(face1.png 至 face9.png),都放在 res\drawable 目錄下。

接著在螢幕上放一個最多顯示 3 行(可輸入多行)的 EditText 和一個 Button,佈局代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:id="@+id/edittext" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:lines="3" android:gravity="left|top"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="隨機插入表情"
android:onClick="onClick_RandomFace" android:layout_marginTop="10dp" />
</LinearLayout>

上述 <EditText> 標籤把 android:gravity 設為 left|top,讓輸入的文字從左上角開始顯示;若不設定,文字會從左側中央開始顯示(因為設了 android:lines="3",EditText 可同時顯示三行,才會有這個問題;若只顯示一行則不受影響)。

<Button> 標籤的 android:onClick 指定了單擊事件方法(onClick_RandomFace),該方法會隨機取得 face1.png 至 face9.png 中任一圖片資源的 ID。最常見的做法是把這 9 個資源 ID 放進陣列,再隨機產生索引取出對應的 ID。但本例改用另一種方式——直接透過反射技術從 R.drawable 類中取得圖片資源 ID。這種做法的好處是,當圖片資源非常多時,就不必在陣列中逐一定義,也能取得任意資源 ID。

前面曾用 <img> 標籤插入圖像,在 EditText 中插入圖像雖也可用這方式,但本例採用更簡單的方法——使用 android.text.style.ImageSpan 類直接插入圖像。具體實作如下:

public void onClick_RandomFace(View view)
{
// 隨機產生1至9的整數
int randomId = 1 + new Random().nextInt(9);
try
{
// 根據隨機產生的1至9的整數從R.drawable類中獲得相應資源ID(靜態變量)的Field對象
Field field = R.drawable.class.getDeclaredField("face" + randomId);
// 獲得資源ID的值,也就是靜態變量的值
int resourceId = Integer.parseInt(field.get(null).toString());
// 根據資源ID獲得資源圖像的Bitmap對象
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceId);
// 根據Bitmap對象創建ImageSpan對象
ImageSpan imageSpan = new ImageSpan(this, bitmap);
// 創建一個SpannableString對象,以便插入用ImageSpan對象封裝的圖像
SpannableString spannableString = new SpannableString("face");
// 用ImageSpan對象替換face
spannableString.setSpan(imageSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// 將隨機獲得的圖像追加到EditText控件的最後
edittext.append(spannableString);
}
catch (Exception e)
{
}
}

撰寫上述代碼需注意以下幾點:

1. 由於 R.drawable 中的資源 ID 都是 public 的靜態變數,可直接用 Field.get 取得這些變數的值;若是 private 或 protected 變數,則需先呼叫 field.setAccessible(true) 設定存取權限才能讀寫。

2. 用 Field.get 取值時,若為靜態變數,參數設為 null 即可;若非靜態變數,則需傳入該變數所在類的物件作為參數。

3. 由於 EditText 類不能直接插入 Span 物件,因此需先用 SpannableString 物件封裝 Span 物件(如本例的 ImageSpan),再把 SpannableString 插入 EditText 中。

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