編輯:關於 Android 程式設計
系統原生的 ListView 在按下時只有一整塊矩形的高亮,放在圓角卡片式的介面裡顯得突兀。想讓高亮跟著外框走圓角,做法是攔截觸碰事件,依點擊位置換上對應的 selector 背景。
關鍵在於「首項」、「中間項」、「尾項」以及「只有一項」這四種狀態,各自需要不同的圓角 shape:四個角都圓、只有上面兩角圓、只有下面兩角圓、完全沒有圓角。因此我們在 onInterceptTouchEvent 中判斷被按下的是第幾個 item,再動態設定 selector。
public class CornerListView extends ListView {
public CornerListView(Context context) { super(context); }
public CornerListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CornerListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
int x = (int) ev.getX();
int y = (int) ev.getY();
int itemnum = pointToPosition(x, y);
if (itemnum == AdapterView.INVALID_POSITION) break;
if (itemnum == 0) {
if (itemnum == getAdapter().getCount() - 1) {
setSelector(R.drawable.app_list_corner_round); // 只有一項
} else {
setSelector(R.drawable.app_list_corner_round_top); // 首項
}
} else if (itemnum == getAdapter().getCount() - 1) {
setSelector(R.drawable.app_list_corner_round_bottom); // 尾項
} else {
setSelector(R.drawable.app_list_corner_shape); // 中間項
}
break;
case MotionEvent.ACTION_UP:
break;
}
return super.onInterceptTouchEvent(ev);
}
}
全部寫在 res/drawable 下,配色與漸層一致,只差 corners 的範圍。
app_list_corner_round.xml(四角皆圓)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
<gradient android:startColor="#BFEEFF"
android:endColor="#40B9FF"
android:angle="270"/>
<corners android:topLeftRadius="6dip"
android:topRightRadius="6dip"
android:bottomLeftRadius="6dip"
android:bottomRightRadius="6dip"/>
</shape>
app_list_corner_round_top.xml(僅上方兩角)
<corners android:topLeftRadius="6dip"
android:topRightRadius="6dip"/>
app_list_corner_round_bottom.xml(僅下方兩角)
<corners android:bottomLeftRadius="6dip"
android:bottomRightRadius="6dip"/>
app_list_corner_shape.xml(中間項,直角)
<shape xmlns:android="https://schemas.android.com/apk/res/android">
<gradient android:startColor="#BFEEFF"
android:endColor="#40B9FF"
android:angle="270"/>
</shape>
寫好之後完全不用改動既有邏輯,只要在版面檔裡把原本的 <ListView> 換成 <CornerListView>(記得帶完整套件名稱),Activity 中的程式碼一行都不用改,就能直接沿用原本的 adapter 與監聽器。
需要留意的是這種做法在每次 ACTION_DOWN 時都會呼叫 setSelector,若列表很長且 frequently 觸發,可以考慮加上判斷避免重複設定。另外若要支援不同圓角半徑,把 6dip 抽成 dimens 資源會更好維護。
Android中使用WebSocket實現群聊與消息推送(脫離WebView)
WebSocket是HTML5的一種新協議,它實現了浏覽器與服務器之間的全雙工通信(full-duplex)。作為Web2.0時代的新產物,它用於彌補HTTP協議的某些不
OpenCV for Android 人臉識別入門:從相冊選圖到框選臉部
在 Android 上做人臉識別,OpenCV 是常見的選擇。透過 Java API,開發者可以較快完成環境建置與基本流程,例如從相冊選圖、轉換成 OpenCV 可用的
OpenGLES 2.0 入門概念整理
OpenGL ES 是針對嵌入式設備的圖形 API,常用於 Android 的 2D 與 3D 繪圖。它具備跨平台特性,並依設備能力提供不同版本。 版本與特性 Open
踩坑筆記:Android Service 中 Toast 不顯示的原因與解法
做 Service 練習時,我在 onCreate、onStart、onDestroy 三個方法裡都像 Activity 那樣呼叫了 Toast.makeText,並用兩