編輯:關於 Android 程式設計
聊天應用裡的表情面板,是個很值得拆開來研究的經典題目。它同時牽涉到格狀列表、多頁切換、手勢翻頁與鍵盤協同,本文就一步步把整個實作攤開來看。
這裡需要兩個關鍵元件:GridView 用來放表情,ViewFlipper 用來承載多頁。因為表情數量通常超過一頁,所以要把 GridView 放進 ViewFlipper 裡,每頁一個 GridView,形成可切換的多頁結構。
GridView 和 ListView 很像,都需要自訂 Adapter,差別只在排列方式:ListView 是一列一列往下排,GridView 則是以格子鋪開。因此完全可以沿用 ListView 的寫法。另外有兩個經常會用到的方法:
setNumColumns() — 設定欄數。setSelector(new ColorDrawable(Color.TRANSPARENT)) — 把選中格子的底色設為透明,預設會是橘黃色,看起來很突兀。<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent" >
<ImageView
android:id="@+id/gridImage"
android:layout_width="30dip"
android:layout_height="30dip"
android:layout_margin="10dip"/>
</RelativeLayout>
結構上和 ListView 的 Adapter 幾乎一致,只是這裡額外用了 ViewHolder 來快取子 View,並在點擊時把表情名稱寫回 EditText:
class MyGridAdapter extends BaseAdapter {
Context context;
ArrayList<HashMap<String, Object>> list;
int layout;
String[] from;
int[] to;
public MyGridAdapter(Context context, ArrayList<HashMap<String, Object>> list,
int layout, String[] from, int[] to) {
super();
this.context = context;
this.list = list;
this.layout = layout;
this.from = from;
this.to = to;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
class ViewHolder {
ImageView image = null;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(layout, null);
holder = new ViewHolder();
holder.image = (ImageView) convertView.findViewById(to[0]);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.image.setImageResource((Integer) list.get(position).get(from[0]));
class MyGridImageClickListener implements OnClickListener {
int position;
public MyGridImageClickListener(int position) {
super();
this.position = position;
}
@Override
public void onClick(View v) {
editText.append((String) list.get(position).get("faceName"));
}
}
// 這裡用了一個方法內部類
holder.image.setOnClickListener(new MyGridImageClickListener(position));
return convertView;
}
}
寫好之後,在 Java 端用 findViewById() 取得 GridView 並設定 Adapter 即可,資料怎麼準備後面再談。
ViewFlipper 負責翻頁效果。有多頁表情時,把每個 GridView 當成它的一個 ChildView 加進去,再透過觸摸監聽實現滑動切頁。這個思路和先前做過的 ImageSwitcher 其實如出一轍。
常用方法:
addView() — 加入 ChildView。setDisplayedChild(int index) — 指定要顯示的子 View。getDisplayedChild() — 取得目前顯示的索引。showNext() / showPrevious() — 顯示下一頁/上一頁。這裡有個坑:把 GridView 放進 ViewFlipper 之後,ViewFlipper 自己的 onTouchListener 會失效。因此翻頁手勢要掛在 GridView 上,由 GridView 的監聽器判斷滑動方向再驅動翻頁。
class MyTouchListener implements OnTouchListener {
ViewFlipper viewFlipper = null;
public MyTouchListener(ViewFlipper viewFlipper) {
super();
this.viewFlipper = viewFlipper;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
moveable = true;
break;
case MotionEvent.ACTION_MOVE:
if (moveable) {
if (event.getX() - startX > 60) {
moveable = false;
int childIndex = viewFlipper.getDisplayedChild();
// 這個 if 是為了防止表情列表循環滑動
if (childIndex > 0) {
viewFlipper.setInAnimation(
AnimationUtils.loadAnimation(ChatActivity.this, R.anim.left_in));
viewFlipper.setOutAnimation(
AnimationUtils.loadAnimation(ChatActivity.this, R.anim.right_out));
viewFlipper.showPrevious();
setPointEffect(childIndex - 1);
}
} else if (event.getX() - startX < -60) {
moveable = false;
int childIndex = viewFlipper.getDisplayedChild();
// 同樣用來防止循環滑動
if (childIndex < listGrid.size() - 1) {
viewFlipper.setInAnimation(
AnimationUtils.loadAnimation(ChatActivity.this, R.anim.right_in));
viewFlipper.setOutAnimation(
AnimationUtils.loadAnimation(ChatActivity.this, R.anim.left_out));
viewFlipper.showNext();
setPointEffect(childIndex + 1);
}
}
}
break;
case MotionEvent.ACTION_UP:
moveable = true;
break;
default:
break;
}
return false;
}
}
接著要解決資料配置與分頁的問題。這裡設計了兩個方法:一個依據表情圖片資源陣列 faceId[] 與名稱陣列 faceName[] 自動產生 GridView 的資料源;另一個則負責把多個 GridView 設定好監聽器後加進 ViewFlipper。
private void addFaceData() {
ArrayList<HashMap<String, Object>> list = null;
for (int i = 0; i < faceId.length; i++) {
if (i % 14 == 0) {
list = new ArrayList<HashMap<String, Object>>();
listGrid.add(list);
}
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("image", faceId[i]);
map.put("faceName", faceName[i]);
// 把表情名稱一起放進資料物件,點擊時就能取得對應名稱
listGrid.get(i / 14).add(map);
}
System.out.println("listGrid size is " + listGrid.size());
}
private void addGridView() {
for (int i = 0; i < listGrid.size(); i++) {
View view = LayoutInflater.from(this).inflate(R.layout.view_item, null);
GridView gv = (GridView) view.findViewById(R.id.myGridView);
gv.setNumColumns(5);
gv.setSelector(new ColorDrawable(Color.TRANSPARENT));
MyGridAdapter adapter = new MyGridAdapter(this, listGrid.get(i),
R.layout.chat_grid_item, new String[]{"image"}, new int[]{R.id.gridImage});
gv.setAdapter(adapter);
gv.setOnTouchListener(new MyTouchListener(viewFlipper));
viewFlipper.addView(view);
// 這裡不習慣用 Java 程式設定邊框,所以另外配置了一個 ImageView 的版面檔
View pointView = LayoutInflater.from(this).inflate(R.layout.point_image_layout, null);
ImageView image = (ImageView) pointView.findViewById(R.id.pointImageView);
image.setBackgroundResource(R.drawable.qian_point);
pagePoint.addView(pointView);
// 放進 pointList,方便後續切換圓點顏色
pointList.add(image);
}
}
每 14 個表情切成一頁,這個數字可以依欄數與螢幕高度自行調整。addGridView() 的最後一段,就是在產生效果圖最下方那排頁碼圓點。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/chat_title"
android:layout_width="match_parent"
android:layout_height="44dip"
android:layout_alignParentTop="true"
android:background="@drawable/chat_title_layer">
<Button
android:id="@+id/chat_msg_button"
android:text="消息(0)"
android:layout_weight="1.9"
... />
<TextView
android:id="@+id/chat_contact_name"
android:text="龍行天下"
android:layout_weight="1"
... />
<ImageButton
android:id="@+id/chat_contact_button"
android:layout_weight="2"
... />
</LinearLayout>
<RelativeLayout
android:id="@+id/faceLayout"
android:layout_width="match_parent"
android:layout_height="1dip"
android:layout_alignParentBottom="true">
<ViewFlipper
android:id="@+id/faceFlipper"
android:layout_width="match_parent"
android:layout_height="130dip"
android:background="#d0d3d5" >
</ViewFlipper>
<LinearLayout
android:id="@+id/fill_the_gap"
android:layout_width="match_parent"
android:layout_height="1dip"
android:background="#272b34"
android:orientation="horizontal">
</LinearLayout>
<LinearLayout
android:id="@+id/pagePoint"
android:layout_width="match_parent"
android:layout_height="20dip"
android:layout_below="@id/faceFlipper"
android:background="#d0d3d5"
android:gravity="center"
android:orientation="horizontal">
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="@+id/chat_bottom_linear"
android:layout_width="match_parent"
android:layout_height="42dip"
android:layout_above="@id/faceLayout"
android:orientation="horizontal">
<ImageButton android:id="@+id/chat_bottom_look" ... />
<ImageButton android:id="@+id/chat_bottom_add" ... />
<EditText android:id="@+id/chat_bottom_edittext" ... />
<Button android:id="@+id/chat_bottom_sendbutton" android:text="發送" ... />
</LinearLayout>
<ListView
android:id="@+id/chat_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/chat_title"
android:layout_above="@id/chat_bottom_linear"
android:fadingEdge="none"
android:background="#f0f0f0"
android:divider="#aaaaaa"
android:dividerHeight="0px">
</ListView>
</RelativeLayout>
其中 id 為 pagePoint 的 LinearLayout,就是我用來放頁碼圓點的容器(ViewGroup)。ViewFlipper 裡有幾個子 View,就動態 addView 幾個圓點,這一點在 addGridView() 中已經體現。為了讓視覺效果更精緻,每個圓點都另外寫了版面檔:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/pointImageView"
android:layout_width="6dip"
android:layout_height="6dip"
android:layout_marginLeft="8dip"
android:layout_marginRight="8dip"/>
</LinearLayout>
本例中關閉表情面板的做法,是把 id 為 faceLayout 的 RelativeLayout 高度設為 1dip。我希望能做到「每次關掉再打開都回到第一頁」,跟官方 QQ 的行為一致。問題是,如果 ViewFlipper 在螢幕上一個像素都沒有顯示,setDisplayedChild(0) 就無法生效,所以高度必須設為 1dip 而不是 0dip。
但這樣一來,螢幕最下方就會多出一條白線,不好看。因此我在 ViewFlipper 上方疊了一條 1dip 高的色塊把它「封住」。有興趣可以自己試著把高度設成 0dip,會發現操作體驗明顯變差。
這裡封裝了一個統一的開合方法:
private void setFaceLayoutExpandState(boolean isexpand) {
if (isexpand == false) {
viewFlipper.setDisplayedChild(0);
ViewGroup.LayoutParams params = faceLayout.getLayoutParams();
params.height = 1;
faceLayout.setLayoutParams(params);
// height 不設為 0,是為了讓再次打開時 ViewFlipper 已初始化在第一頁,
// 避免出現畫面滑動的殘影。
// 而 1dip 產生的白縫,則由 ViewFlipper 上層那個 1dip 色塊遮住。
// 另外,ViewFlipper 必須在螢幕上佔有像素,setDisplayedChild() 才會生效。
chatBottomLook.setBackgroundResource(R.drawable.chat_bottom_look);
} else {
// 讓軟鍵盤消失
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(
ChatActivity.this.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
ViewGroup.LayoutParams params = faceLayout.getLayoutParams();
params.height = 150;
faceLayout.setLayoutParams(params);
chatBottomLook.setBackgroundResource(R.drawable.chat_bottom_keyboard);
}
}
為了貼近官方版的互動感受,表情面板和軟鍵盤需要能互相切換,這就牽涉到對輸入法Manager的操作。
隱藏鍵盤:
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(
ChatActivity.this.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
切換鍵盤狀態(原本開啟就關閉,原本關閉就開啟):
((InputMethodManager) ChatActivity.this.getSystemService(INPUT_METHOD_SERVICE))
.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
整套機制的關鍵其實只有幾件事:GridView 負責排表情、ViewFlipper 負責分頁、手勢監聽負責翻頁,最後用高度切換把面板收進螢幕外。剩下的都是細節打磨。
Android Studio 2.1.3 搭配 gradle-experimental 編譯使用 OpenCV 完整教學
在 Android Studio 中進行 JNI 開發時,有一個實驗性的 gradle-experimental 工具相當好用。它最大的優點是不必另外撰寫 Android
Fragment 狀態保存的三大坑與 StatedFragment 通用解決方案
和 Activity 一樣,Fragment 也有 onSaveInstanceState() 回調。但實踐中會發現,這個方法在 Fragment 上「非常不靠譜」:屏幕
TabLayout 搭配 ViewPager 踩坑記:Tab 為什麼全部消失?
把 TabLayout 和 ViewPager 一起用時,我遇到了一個相當惱人的問題。以下先還原我照官方範例寫出來的程式碼。 原始寫法 布局檔: <Linear
Android GPS 定位資料取得:LocationManager 與位置監聽
LocationManager 是定位核心Android 的定位服務主要由 LocationManager 管理。應用可透過 getSystemService 取得它,再