Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 如何實現投票/觀點表達界面:標籤流式佈局與狀態切換

編輯:關於 Android 程式設計

先上效果圖:

這個界面有兩個核心技術點:一是把一堆「觀點標籤」按屏幕寬度自動換行排列;二是點擊後有按下態的視覺反饋。

一、容器:一個豎向 LinearLayout


注意初始 visibility="gone",數據準備好之後再由代碼切換為可見,避免佈局閃現。

二、每個標籤:自定義 KXTagWidget

標籤本質就是一個帶邊框的 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 省略
}

三、Activity:流式排布算法

關鍵在 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 ArrayList mTagList = 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 中統一排布,性能會更好一些。

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