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

Android 項目實戰(二十三):仿 QQ 實現 App 全局字體大小調整

編輯:關於 Android 開發

Android 項目實戰(二十三):仿 QQ 實現 App 全局字體大小調整

一、需求

這個項目的目標用戶是中老年人,產品因此提出了一個要求:支持全局調整 App 的字體大小。交互方式參考 QQ。

QQ 的處理很講究:滑動下方的 seekbar 時,只有當手指滑到某個刻度上,上半部分的預覽區域才會改變文字大小;拖動過程中字體並不跟著連續變化。離開這個界面後,App 整體的文字大小就按新設定渲染了。

二、實現思路

1、給文字分級。先把 App 內所有文本歸檔,分成 3 到 5 個級別(具體看需求)。比如標題欄的 TextView 定為級別 1(默認 24sp),類似地定級別 2(22sp)等等。這一步不能偷懶——如果每個 TextView 的字號都亂七八糟,那「調整字體大小」這個功能本身就失去意義了。

2、用一個靜態變量記錄當前級別。在 Constant 類裡建一個靜態變量,取值範圍就是 seekbar 的刻度數。Demo 裡限制為四檔:小、標準、大、特大,那麼 TEXT_SIZE 的取值就是 0、1、2、3。

public class Constant {
    public static int TEXT_SIZE = 0;
}

3、滑到刻度才刷新。滑動 seekbar,當抵達某個刻度時才更新靜態變量的值,並刷新預覽列表的適配器。注意這裡絕不能「一滑動就刷新」,必須等到刻度。

4、退出時持久化。離開設置界面時用 SharedPreferences 保存,每次進入 App 時讀回來。然後在每個 Activity 或 Fragment 創建視圖的過程中,給 TextView 動態設置字號:

textView.setTextSize(級別默認字號 + Constant.TEXT_SIZE * 3);

整體思路就是:一個標記變量記錄級別並用 SharedPreferences 持久化,在界面創建視圖時給 TextView 動態套用字號。

這裡要特別注意:並不是改完字號,App 裡所有已打開界面的 TextView 會立刻變化,而是新創建的界面才會套用新值。QQ 也是這個行為——回到上一頁字體就變了。如果要求即時全局生效,那就得引入資源覆蓋或自定義 TextView 統一管理的方案,複雜度會高一截。

三、代碼實現

1、自定義帶刻度的 SeekBar。系統自帶的 SeekBar 沒有刻度與文字標籤,滿足不了需求。這裡用了一個自定義控件,繼承自 View 而非 SeekBar,因此監聽只能靠接口回調:

public class CustomSeekbar extends View {

    private int width;
    private int height;
    private float scale = 0;
    private int perWidth = 0;
    private Paint mPaint;
    private Paint mTextPaint;
    private Paint buttonPaint;
    private Canvas canvas;
    private Bitmap bitmap;
    private Bitmap thumb;
    private Bitmap spot;
    private Bitmap spot_on;
    private int hotarea = 100;          // 點擊的熱區
    private int cur_sections = 2;       // 當前所處刻度
    private ResponseOnTouch responseOnTouch;
    private int bitMapHeight = 38;      // 第一個點的起始位置,圖片長寬 76,取一半
    private int textMove = 60;          // 字與下方點的距離
    private int[] colors = new int[]{0xffdf5600, 0x33000000}; // 已選中橙色、未選中灰色
    private int textSize;
    private int circleRadius;
    private ArrayList<String> section_title;

    public CustomSeekbar(Context context) {
        super(context);
    }

    public CustomSeekbar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomSeekbar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        cur_sections = 0;
        bitmap = Bitmap.createBitmap(900, 1100, Bitmap.Config.ARGB_8888);
        canvas = new Canvas();
        canvas.setBitmap(bitmap);
        thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.img_setting_seekbar_thumbe_large);
        spot = BitmapFactory.decodeResource(getResources(), R.mipmap.img_setting_seekbar_thumbe);
        spot_on = BitmapFactory.decodeResource(getResources(), R.mipmap.img_setting_seekbar_thumbe);
        bitMapHeight = thumb.getHeight() / 2;
        textMove = bitMapHeight + 5;
        textSize = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());
        circleRadius = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 3, getResources().getDisplayMetrics());
        mPaint = new Paint(Paint.DITHER_FLAG);
        mPaint.setAntiAlias(true); // 鋸齒不顯示
        mPaint.setStrokeWidth(3);
        mTextPaint = new Paint(Paint.DITHER_FLAG);
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(textSize);
        mTextPaint.setColor(0xffb5b5b4);
        buttonPaint = new Paint(Paint.DITHER_FLAG);
        buttonPaint.setAntiAlias(true);
    }

    /**
     * 實例化後調用,設置 bar 的段數和文字
     */
    public void initData(ArrayList<String> section) {
        if (section != null) {
            section_title = section;
        } else {
            // 未傳入正確的分級數據時,默認使用「低」「中」「高」
            String[] str = new String[]{"低", "中", "高"};
            section_title = new ArrayList<String>();
            for (int i = 0; i < str.length; i++) {
                section_title.add(str[i]);
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        width = widthSize;
        float scaleX = widthSize / 1080f;
        float scaleY = heightSize / 1920f;
        scale = Math.max(scaleX, scaleY);

        height = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 62, getResources().getDisplayMetrics());
        setMeasuredDimension(width, height);

        width = width - bitMapHeight / 2;
        perWidth = (width - section_title.size() * spot.getWidth() - thumb.getWidth() / 2)
                / (section_title.size() - 1);
        hotarea = perWidth / 2;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setColor(Color.WHITE);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAlpha(0);
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);
        canvas.drawBitmap(bitmap, 0, 0, null);

        mPaint.setAlpha(255);
        mPaint.setColor(colors[1]);
        canvas.drawLine(bitMapHeight, height * 2 / 3,
                width - bitMapHeight - spot_on.getWidth() / 2, height * 2 / 3, mPaint);

        int section = 0;
        while (section < section_title.size()) {
            if (section < cur_sections) {
                mPaint.setColor(colors[0]);
                canvas.drawLine(thumb.getWidth() / 2 + section * perWidth + (section + 1) * spot_on.getWidth(),
                        height * 2 / 3,
                        thumb.getWidth() / 2 + section * perWidth + (section + 1) * spot_on.getWidth() + perWidth,
                        height * 2 / 3, mPaint);
                canvas.drawBitmap(spot_on,
                        thumb.getWidth() / 2 + section * perWidth + section * spot_on.getWidth(),
                        height * 2 / 3 - spot_on.getHeight() / 2, mPaint);
            } else {
                mPaint.setAlpha(255);
                if (section == section_title.size() - 1) {
                    canvas.drawBitmap(spot, width - spot_on.getWidth() - bitMapHeight / 2,
                            height * 2 / 3 - spot.getHeight() / 2, mPaint);
                } else {
                    canvas.drawBitmap(spot,
                            thumb.getWidth() / 2 + section * perWidth + section * spot_on.getWidth(),
                            height * 2 / 3 - spot.getHeight() / 2, mPaint);
                }
            }

            if (section == section_title.size() - 1) {
                canvas.drawText(section_title.get(section),
                        width - spot_on.getWidth() - bitMapHeight / 4 - textSize / 2,
                        height * 2 / 3 - textMove, mTextPaint);
            } else {
                canvas.drawText(section_title.get(section),
                        thumb.getWidth() / 2 + section * perWidth + section * spot_on.getWidth(),
                        height * 2 / 3 - textMove, mTextPaint);
            }
            section++;
        }

        if (cur_sections == section_title.size() - 1) {
            canvas.drawBitmap(thumb,
                    width - spot_on.getWidth() - bitMapHeight / 2 - thumb.getWidth() / 2,
                    height * 2 / 3 - bitMapHeight, buttonPaint);
        } else {
            canvas.drawBitmap(thumb,
                    thumb.getWidth() / 2 + cur_sections * perWidth + cur_sections * spot_on.getWidth() - thumb.getWidth() / 4,
                    height * 2 / 3 - bitMapHeight, buttonPaint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.img_setting_seekbar_thumbe_large);
                responseTouch((int) event.getX());
                break;
            case MotionEvent.ACTION_MOVE:
                thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.img_setting_seekbar_thumbe_large);
                responseTouch((int) event.getX());
                break;
            case MotionEvent.ACTION_UP:
                thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.img_setting_seekbar_thumbe_large);
                responseTouch((int) event.getX());
                // 只在手指抬起時回調,滿足「拖動過程不變化」的需求
                responseOnTouch.onTouchResponse(cur_sections);
                break;
        }
        return true;
    }

    private void responseTouch(int x) {
        if (x <= width - bitMapHeight / 2) {
            cur_sections = (x + perWidth / 3) / perWidth;
        } else {
            cur_sections = section_title.size() - 1;
        }
        invalidate();
    }

    /**
     * 設置監聽。因為本控件繼承的是 View 而不是 SeekBar,
     * 所以只能用接口來實現到達刻度的回調
     */
    public void setResponseOnTouch(ResponseOnTouch response) {
        responseOnTouch = response;
    }

    /**
     * 設置進度
     */
    public void setProgress(int progress) {
        cur_sections = progress;
        invalidate();
    }
}

關鍵點在 onTouchEvent:ACTION_DOWN 和 ACTION_MOVE 只更新畫面,唯有 ACTION_UP 才觸發 onTouchResponse 回調。這正好對應了 QQ 那種「松手才生效」的手感。

2、回調接口

public interface ResponseOnTouch {
    public void onTouchResponse(int volume);
}

3、使用方式

private CustomSeekbar seekBar;
seekBar = (CustomSeekbar) findViewById(R.id.progressBar);

// 這個集合用於給自定義 SeekBar 設置刻度級別,集合裡有幾個數據就有幾個刻度
ArrayList<String> volume_sections = new ArrayList<String>();
volume_sections.add("小");
volume_sections.add("標準");
volume_sections.add("大");
volume_sections.add("特大");

seekBar.initData(volume_sections);
seekBar.setProgress(Constant.TEXT_SIZE); // 設置默認級別
seekBar.setResponseOnTouch(this);        // Activity 實現 ResponseOnTouch 接口

實現接口:

@Override
public void onTouchResponse(int volume) {
    // 參數 volume 就是級別,集合有 4 個數據時,volume 取值為 0、1、2、3
    Constant.TEXT_SIZE = volume;
    // 這裡用 SharedPreferences 保存該靜態變量
    // 刷新列表,查看文字改變後的效果
    adapter.notifyDataSetChanged();
}

列表適配器裡設置字號:

holder.community_doctor_name.setTextSize(該TextView級別默認字號 + Constant.TEXT_SIZE * 5);

效果圖後續補上。

這是我個人的實現思路,局限性肯定是有的——比如級別與倍數的換算寫死了,比如新界面才生效而非全局即時刷新。歡迎提出修改意見。

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