編輯:關於 Android 開發
要做的畫面類似手機 QQ 的對話列表:頭像是圓的,每一列往左滑會出現「置頂」與「刪除」。這裡用到兩個技術點——側滑選單套件,以及自定義圓形 ImageView。
側滑的部分沿用開源專案 SwipeMenuListView(https://github.com/baoyongzhang/SwipeMenuListView );至于「左右滑動刪除 ListView 項目」這種更輕量的互動,則可以參考另一個開源框架 Android-SwipeToDismiss(https://github.com/romannurik/Android-SwipeToDismiss ),它的目標很單純:手指左滑或右滑時,直接把該項目移除。
先把相關類別放進專案結構中:

核心概念是 BitmapShader 搭配 canvas.drawCircle:把圖片當成 shader 填進一個圓形區域,於是頭像就變圓了。這裡列出關鍵片段,完整類別可直接從專案取用。
public class CircleImageView extends ImageView {
private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;
private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
private final RectF mDrawableRect = new RectF();
private final RectF mBorderRect = new RectF();
private final Matrix mShaderMatrix = new Matrix();
private final Paint mBitmapPaint = new Paint();
private final Paint mBorderPaint = new Paint();
private Bitmap mBitmap;
private BitmapShader mBitmapShader;
private int mBitmapWidth, mBitmapHeight;
private float mDrawableRadius, mBorderRadius;
private int mBorderColor = Color.BLACK;
private int mBorderWidth = 0; // 0 表示不畫漸變邊框
private boolean mReady;
private boolean mSetupPending;
@Override
protected void onDraw(Canvas canvas) {
if (getDrawable() == null) return;
// 用圓形裁切繪製圖片
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius, mBitmapPaint);
if (mBorderWidth != 0) {
canvas.save();
canvas.rotate(20, getWidth() / 2, getHeight() / 2);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius, mBorderPaint);
canvas.restore();
}
}
private void setup() {
if (!mReady) { mSetupPending = true; return; }
if (mBitmap == null) return;
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true); // 去鋸齒,圓邊才不會毛
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(0, 0, getWidth(), getHeight());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2,
(mBorderRect.width() - mBorderWidth) / 2);
mDrawableRect.set(mBorderWidth, mBorderWidth,
mBorderRect.width() - mBorderWidth,
mBorderRect.height() - mBorderWidth);
mDrawableRadius = Math.min(mDrawableRect.height() / 2, mDrawableRect.width() / 2);
// SweepGradient 做出天藍色漸變邊框
Shader sweepGradient = new SweepGradient(getWidth() / 2, getHeight() / 2,
new int[] { Color.rgb(255, 255, 255), Color.rgb(1, 209, 255) }, null);
mBorderPaint.setShader(sweepGradient);
updateShaderMatrix();
invalidate();
}
/** 依容器大小計算縮放比例,並置中,相當於 CENTER_CROP */
private void updateShaderMatrix() {
float scale;
float dx = 0, dy = 0;
mShaderMatrix.set(null);
if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
scale = mDrawableRect.height() / (float) mBitmapHeight;
dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
} else {
scale = mDrawableRect.width() / (float) mBitmapWidth;
dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
}
mShaderMatrix.setScale(scale, scale);
mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth,
(int) (dy + 0.5f) + mBorderWidth);
mBitmapShader.setLocalMatrix(mShaderMatrix);
}
}
實作上有兩個關鍵細節:setAntiAlias(true) 若少了,圓形邊緣會出現鋸齒;updateShaderMatrix 負責把圖片等比放大到足以鋪滿圓形並置中,效果等同 CSS 的 cover。另外這個類別刻意鎖死了 ScaleType 只能為 CENTER_CROP,也禁止 adjustViewBounds,因為圓形裁切只有在這個模式下才成立。
public class MainActivity extends Activity {
private ArrayList<String> data;
private MyAdapter mMyAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 模擬對話內容
String[] str = {
"今天天氣不錯!", "你好啊,在嗎?", "朋友有空出來完。", "走,出去嗨!",
"帥哥有空嗎?", "來家裡玩。", "QQ群有新動態。", "騰訊新聞:伊拉克發動戰爭!",
"QQ紅包,快來領", "QQ健康", "QQ郵箱"
};
data = new ArrayList<String>();
for (String n : str) data.add(n);
// 建立側滑提示框
SwipeMenuCreator creator = new SwipeMenuCreator() {
@Override
public void create(SwipeMenu menu) {
// 置頂
SwipeMenuItem zhidingitem = new SwipeMenuItem(getApplicationContext());
zhidingitem.setBackground(new ColorDrawable(Color.GRAY));
zhidingitem.setWidth(dp2px(90));
zhidingitem.setTitle("置頂");
zhidingitem.setTitleSize(15);
zhidingitem.setTitleColor(Color.WHITE);
menu.addMenuItem(zhidingitem);
// 刪除
SwipeMenuItem deleteitem = new SwipeMenuItem(getApplicationContext());
deleteitem.setBackground(new ColorDrawable(Color.RED));
deleteitem.setWidth(dp2px(90));
deleteitem.setTitle("刪除");
deleteitem.setTitleSize(15);
deleteitem.setTitleColor(Color.WHITE);
menu.addMenuItem(deleteitem);
}
};
SwipeMenuListView smlv = (SwipeMenuListView) findViewById(R.id.smlv);
smlv.setMenuCreator(creator);
smlv.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
// index 對應提示框的順序,position 是列的下標
switch (index) {
case 0: // 置頂:取出該列,移到集合頭部
String str = data.get(position);
data.remove(position);
data.add(0, str);
mMyAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "置頂成功!", 0).show();
break;
case 1: // 刪除
data.remove(position);
mMyAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "刪除成功!", 0).show();
break;
default:
break;
}
return false;
}
});
mMyAdapter = new MyAdapter(this, -1);
smlv.setAdapter(mMyAdapter);
}
private class MyAdapter extends ArrayAdapter {
LayoutInflater flater;
public MyAdapter(Context context, int resource) {
super(context, resource);
flater = LayoutInflater.from(context);
}
@Override public int getCount() {
return data.size();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = flater.inflate(R.layout.list, null);
ImageView iv = (ImageView) convertView.findViewById(R.id.iv);
iv.setImageResource(R.drawable.qqq); // 這裡換成 CircleImageView 就是圓頭像
TextView tv = (TextView) convertView.findViewById(R.id.tv);
tv.setText(data.get(position));
return convertView;
}
}
public int dp2px(float dipValue) {
final float scale = this.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
}
主布局只要放一個 SwipeMenuListView:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.baoyz.swipemenulistview.SwipeMenuListView
android:id="@+id/smlv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
列表項布局則把 ImageView 換成自定義的圓形頭像類別:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="10dp">
<com.lixu.qqchehua.CircleImageView
android:id="@+id/iv"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

補充一點:置頂與刪除都是直接操作 data 集合再呼叫 notifyDataSetChanged(),在真實專案中通常還要同步更新資料庫或後端;另外若頭像是從網路載入,記得加上圖片載入庫並處理快取,避免每次捲動都重新解碼。
Android 手機衛士實作(十):應用管理器中的多類型列表與懸浮標題
應用管理器需要把「用戶應用」與「系統應用」分區展示,並在捲動時於頂部浮出一個標題提示目前所在分區。這兩個需求分別對應 ListView 的多條目類型機制與捲動監聽。
熱修復方案 Tinker 實戰:微信開源的入門與接入指南
熱修復 - Tinker 上手記 微信把 Tinker 開源出來,真是讓人喜出望外,二話不說就得來研究一番。比起 nuwa,Tinker 在各方面都成熟不少,而且 Git
Android 開發實踐:ListView 效能優化解析
讀過一些 vogella 的文章後,我對 Android ListView 的效能優化特別感興趣,於是動手實作,結果效能確實提升不少。 優化前後對比 優化前的 log 截
Android 自定義圖片控件合集:圓角、變換、色彩處理與圖文混排
Android 自定義圖片控件合集 假期留守公司,人少事清,正好拿來練手。這段時間我把網上幾篇講自定義控件與圖片處理的文章(主要參考鴻洋的博客,另外也借鑑了部分思路)反覆