編輯:關於 Android 程式設計
先上效果圖:

這個界面有兩個核心技術點:一是把一堆「觀點標籤」按屏幕寬度自動換行排列;二是點擊後有按下態的視覺反饋。
注意初始 visibility="gone",數據準備好之後再由代碼切換為可見,避免佈局閃現。
標籤本質就是一個帶邊框的 TextView,但需要額外支持「正常態/按下態」兩套顏色,還要能算出自身渲染寬度:
public class KXTagWidget extends TextView {
String mTagName;
/** 顏色相關 */
int mBgColor = Color.WHITE;
int mPressedBgColor = Color.WHITE;
int mTextColor = Color.WHITE;
int mPressedTextColor = Color.BLACK;
public KXTagWidget(Context context) {
super(context);
setClickable(true);
}
public KXTagWidget(Context context, AttributeSet attrs) {
super(context, attrs);
setClickable(true);
}
public KXTagWidget(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setClickable(true);
}
public void setName(String tagName) {
if (tagName != null) {
mTagName = tagName;
this.setText(mTagName);
}
}
public void setBgColor(int bgColor, int pressedBgColor) {
mBgColor = bgColor;
mPressedBgColor = pressedBgColor;
this.setBackgroundColor(bgColor);
}
public void setTextColor(int textColor, int pressedTextColor) {
mTextColor = textColor;
mPressedTextColor = pressedTextColor;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 手繪四條邊形成邊框
Paint paint = new Paint();
paint.setColor(this.mBgColor);
int width = getWidth();
int height = getHeight();
canvas.drawLine(0, 0, width - 1, 0, paint);
canvas.drawLine(width - 1, 0, width - 1, height, paint);
canvas.drawLine(width - 1, height - 1, 0, height - 1, paint);
canvas.drawLine(0, height - 1, 0, 0, paint);
}
/** 計算渲染所需寬度:文字寬 + 左右內邊距 */
public int getMesuredWidth() {
Paint p = this.getPaint();
float textWidth = p.measureText(mTagName);
return (int) textWidth
+ this.getCompoundPaddingLeft()
+ this.getCompoundPaddingRight();
}
// getter / setter 省略
}
關鍵在 constructTagListView()。思路是維護一個「剩餘可用寬度」surplus,逐個標籤嘗試往當前行裡塞;塞得下就放,塞不下就換行並重置 surplus。
private static final int VOTE_BAR_IMAGE_NUM = 9; private int[] mVoteBarImage = new int[VOTE_BAR_IMAGE_NUM]; private int[] mTagBgColor = new int[14]; private TagOnTouchListener mTagOnTouchListener = null; private TagOnClickListener mTagOnClickListener = null; private ArrayListmTagList = new ArrayList (); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initTagBgColor(); mTagList.add("標籤一"); mTagList.add("標籤二"); mTagList.add("標籤三"); mTagList.add("這是一個比較長的觀點描述文字示例"); // ... constructViews(); } private void constructViews() { String text = "一共有 " + 11 + " 項"; TextView view = (TextView) findViewById(R.id.repost_vote_total_num_des); view.setText(text); View answerlistView = findViewById(R.id.repost_vote_anwser_list); View taglistView = findViewById(R.id.repost_vote_tag_list); View inputView = findViewById(R.id.repost_vote_input_layout); answerlistView.setVisibility(View.GONE); taglistView.setVisibility(View.VISIBLE); inputView.setVisibility(View.VISIBLE); constructTagListView(); } /** 前 7 個標籤用漸變紅色系,後 7 個用漸變灰色系 */ private void initTagBgColor() { for (int i = 0; i < 7; ++i) { int r = 231 - i * 18; int g = 85 - i * 3; int b = 85 - i * 3; mTagBgColor[i] = Color.rgb(r, g, b); } for (int i = 7; i < 14; ++i) { int c = 118 + (i - 7) * 14; mTagBgColor[i] = Color.rgb(c, c, c); } } private void constructTagListView() { LinearLayout parent = (LinearLayout) findViewById(R.id.repost_vote_tag_list); if (mTagList == null || mTagList.size() == 0) { parent.setVisibility(View.GONE); return; } parent.removeAllViews(); int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); float totalWidth = screenWidth - 25.0f; int tagTotalNum = Math.min(mTagList.size(), 15); /** 當前行剩餘可用空間 */ float surplus = totalWidth; LayoutParams params = new LayoutParams(); params.width = LayoutParams.FILL_PARENT; params.height = LayoutParams.WRAP_CONTENT; params.bottomMargin = 1; LinearLayout oneLine = new LinearLayout(this); oneLine.setLayoutParams(params); for (int i = 0; i < tagTotalNum; i++) { KXTagWidget oneTag = (KXTagWidget) getLayoutInflater() .inflate(R.layout.kx_widget_view, null); String tagName = mTagList.get(i); oneTag.setName(tagName); oneTag.setTag(i); oneTag.setBgColor(selectTagBgColor(i), Color.WHITE); mTagOnClickListener = new TagOnClickListener(); mTagOnTouchListener = new TagOnTouchListener(); oneTag.setOnClickListener(mTagOnClickListener); oneTag.setOnTouchListener(mTagOnTouchListener); float viewWidth = oneTag.getMesuredWidth(); if (surplus > viewWidth) { // 當前行放得下,直接添加並扣減剩餘空間 oneLine.addView(oneTag); surplus -= viewWidth; } else { // 放不下,先把當前行加入父容器,再開新行 parent.addView(oneLine); surplus = totalWidth; oneLine = new LinearLayout(this); oneLine.setLayoutParams(params); oneLine.addView(oneTag); surplus -= viewWidth; } } if (oneLine != null) { parent.addView(oneLine); } } private int selectTagBgColor(int index) { if (index < mTagBgColor.length) { return mTagBgColor[index]; } return mTagBgColor[mTagBgColor.length - 1]; }
通過 OnTouchListener 在 ACTION_DOWN 時切換配色,抬起或取消時還原:
private class TagOnTouchListener implements OnTouchListener {
@Override
public boolean onTouch(View v, MotionEvent event) {
KXTagWidget tagView = (KXTagWidget) v;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
tagView.setTextColor(tagView.getmPressedTextColor());
tagView.setBackgroundColor(tagView.getmPressedBgColor());
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_OUTSIDE:
case MotionEvent.ACTION_CANCEL:
tagView.setTextColor(tagView.getmTextColor());
tagView.setBackgroundColor(tagView.getmBgColor());
break;
}
return false; // 返回 false,不消費事件,確保 onClick 仍能觸發
}
}
private class TagOnClickListener implements OnClickListener {
@Override
public void onClick(View view) {
Integer tagIndex = (Integer) view.getTag();
String name = mTagList.get(tagIndex);
Toast.makeText(MainActivity.this, name, Toast.LENGTH_LONG).show();
}
}
這裡有個容易踩的坑:onTouch 必須返回 false。如果返回 true,事件被消費,OnClickListener 就永遠不會被調用——你會看到按下變色,但松手後什麼也不發生。
整體來說,這個方案的好處是不依賴任何第三方庫,靠 measureText 手工算寬度就能實現流式排列。如果標籤數量很大或頻繁刷新,可以考慮改成自定義 ViewGroup 在 onMeasure/onLayout 中統一排布,性能會更好一些。
精選 Android 開發工具箱:讓日常瑣事自動化
開發過程中總會遇到一堆小問題,自己動手當然能解決,但有工具相助,效率完全是另一個檔次。以下是我日常會用到的工具清單。 Vysor 把手機畫面投到手機以外的螢幕上,而且可
Android 禁止 ViewPager 滑動
最近項目中有個需求:禁止 ViewPager 的滑動事件。我們看 360 手機助手的界面,風格大概就是這樣——中間內容是不可滑動的。 下面寫個 demo 說明如何禁止
Android Studio 百度地圖開發(二):地圖定位實戰
Android studio 百度地圖開發(2)地圖定位 開發環境:win7 64 位,Android Studio。地圖顯示與工程配置請參考上一篇《Android st
Android 動態加載入門(一):從類加載器與雙親委派談起
動態加載(也就是常說的插件化)在大型專案裡地位不低。App 越做越大,把不常用的模塊拆成插件按需加載,能明顯壓下安裝包與記憶體壓力;另一方面,高頻發版很傷使用者體驗,有了