1. 程式人生 > >Android全域性改變字型大小(坑)

Android全域性改變字型大小(坑)

這邊分享一個功能需求,全域性改變字型大小。當下的情景比較蛋疼…一個祖傳的專案,需要在半路新增這個需求,各種字型大小已經寫明在xml裡面了,dp,sp,甚至xp不等。當時內心是拒絕的,但是由於使用者反饋實在要做,而且app面向的使用者為老年使用者居多,還是決定踩坑了。這裡也善意提醒大家,凡事留一線,日後好給自己留活路。所以,我進入了漫長的百度或者是google…
效果圖
一. 正確的姿勢(我認為)
參考https://blog.csdn.net/mrwangxsyz/article/details/48767555
首先想到的就是通過style設定字型的自定義屬性,重啟當前應用,通過BaseActivity修改屬性識別符號去控制當前字型的大小,當前頁面需要手動設定,貌似都需要,然後要重啟之前的頁面。奈何我這個專案已經過半,在xml中基本是寫死的,比較絕望當時,原本想硬著頭皮繼續下去的….

參考思路連結:
二. 勉強將就的姿勢(成功瞞過產品經理,並且比ios還改的快)
看到網上有一種方式就是字型設定一般是sp,一開始區分dp的時候就隱約記得有一個縮放係數,那麼我們不妨從這裡入手,檢視下原始碼發現是這個scaledDesity
這裡寫圖片描述
那麼我們只需要改變這個引數的大小就可以了,頓時看到了希望
1.思路,首先需要知道的是要改變scaledDesity

 //重寫字型縮放比例 api<25
    @Override
    public Resources getResources() {
        Resources res =super.getResources
(); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) { Configuration config = res.getConfiguration(); config.fontScale= MyApplication.getMyInstance().getFontScale();//1 設定正常字型大小的倍數 res.updateConfiguration(config,res.getDisplayMetrics()); } return res;
}

這裡可以看到在25版本以後的api拋棄了這個方法

 /**
     * Store the newly updated configuration.
     *
     * @deprecated See {@link android.content.Context#createConfigurationContext(Configuration)}.
     */
    @Deprecated
    public void updateConfiguration(Configuration config, DisplayMetrics metrics) {
        updateConfiguration(config, metrics, null);
    }

那麼使用這個方法createConfigurationContext

  //重寫字型縮放比例  api>25
    @Override
    protected void attachBaseContext(Context newBase) {
        if(Build.VERSION.SDK_INT>Build.VERSION_CODES.N){
            final Resources res = newBase.getResources();
            final Configuration config = res.getConfiguration();
        config.fontScale=MyApplication.getMyInstance().getFontScale();//1 設定正常字型大小的倍數
            final Context newContext = newBase.createConfigurationContext(config);
            super.attachBaseContext(newContext);
        }else{
            super.attachBaseContext(newBase);
        }
    }

2.正常情況下需要通知下發關閉前面的設定頁面,然後重啟主頁面。這裡使用EventBus或者RxBus通知會方便一些
這裡使用了RxBus
2.1.RxBus的使用
新增依賴

 compile 'io.reactivex.rxjava2:rxjava:2.0.5'
 compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

RxBus程式碼:

package com.demo.textsizechange;

import android.support.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;


/**
 * Created by RJS on 2016/7/18.
 */
public class RxBus {
    private ConcurrentHashMap<Object, List<Subject>> maps = new ConcurrentHashMap<>();
    private static RxBus instance;

    private RxBus() {
    }
    private static class RxBusHolder{
        private static RxBus instance = new RxBus();
    }
    public static   RxBus getInstance() {
        return RxBusHolder.instance;
    }

    @SuppressWarnings("unchecked")
    public <T> Observable<T> register(@NonNull Object tag, @NonNull Class<T> clazz) {
        List<Subject> subjects = maps.get(tag);
        if (subjects == null) {
            subjects = new ArrayList<>();
            maps.put(tag, subjects);
        }
        Subject<T> subject = PublishSubject.<T>create();
        subjects.add(subject);
        return subject;
    }

    @SuppressWarnings("unchecked")
    public void unregister(@NonNull Object tag, @NonNull Observable observable) {
        List<Subject> subjects = maps.get(tag);
        if (subjects != null) {
            subjects.remove((Subject) observable);
            if (subjects.isEmpty()) {
                maps.remove(tag);
            }
        }
    }

    @SuppressWarnings("unchecked")
    public void post(@NonNull Object o) {
        post(o.getClass().getSimpleName(), o);
    }

    @SuppressWarnings("unchecked")
    public void post(@NonNull Object tag, @NonNull Object o) {
        List<Subject> subjects = maps.get(tag);
        if (subjects != null && !subjects.isEmpty()) {
            for (Subject s : subjects) {
                s.onNext(o);
            }
        }
    }

    /**

     private Observable<String> observable;
     observable = RxBus.getInstance().register(getClassName(), String.class);

     observable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<String>() {
    @Override
    public void call(String s) {
    Log.e("zhang", "receiver "+s);
    }
    });

     RxBus.getInstance().unregister("zhang", zhang);

     RxBus.getInstance().post("zhang", "傳遞資料++++++");


     */
}

3.需要重啟頁面

  //           this.recreate();
                Intent intent = getIntent();
                overridePendingTransition(0, 0);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                finish();
                overridePendingTransition(0, 0);
                startActivity(intent);

5.ok基本上比較清晰了,上程式碼

BaseActivity.java

package com.demo.textsizechange;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

/**
 * Created by zsj on 2016/8/4.
 */
public abstract class BaseActivity extends AppCompatActivity {

    public Observable observable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        observable = RxBus.getInstance().register(this.getClass().getSimpleName(), MessageSocket.class);
        observable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<MessageSocket>() {

            @Override
            public void accept(MessageSocket message) throws Exception {
                rxBusCall(message);
            }
        });
    }

    public void rxBusCall(MessageSocket message) {
    }




    public int getColorById(int resId) {
        return ContextCompat.getColor(this, resId);
    }


    public void goActivity(Class<?> activity) {
        Intent intent = new Intent();
        intent.setClass(getApplicationContext(), activity);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getInstance().unregister(this.getClass().getSimpleName(), observable);
    }


    //重寫字型縮放比例 api<25
    @Override
    public Resources getResources() {
        Resources res =super.getResources();
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) {
            Configuration config = res.getConfiguration();
            config.fontScale= MyApplication.getMyInstance().getFontScale();//1 設定正常字型大小的倍數
            res.updateConfiguration(config,res.getDisplayMetrics());
        }
        return res;
    }
    //重寫字型縮放比例  api>25
    @Override
    protected void attachBaseContext(Context newBase) {
        if(Build.VERSION.SDK_INT>Build.VERSION_CODES.N){
            final Resources res = newBase.getResources();
            final Configuration config = res.getConfiguration();
            config.fontScale=MyApplication.getMyInstance().getFontScale();//1 設定正常字型大小的倍數
            final Context newContext = newBase.createConfigurationContext(config);
            super.attachBaseContext(newContext);
        }else{
            super.attachBaseContext(newBase);
        }
    }



}

使用TextSizeShowActivity

package com.demo.textsizechange;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import fontsliderbar.FontSliderBar;


/**
 * Created by zsj on 2017/9/11.
 * 字型設定展示
 */

public class TextSizeShowActivity extends BaseActivity {
    @BindView(R.id.fontSliderBar)
    FontSliderBar fontSliderBar;
    @BindView(R.id.tv_chatcontent1)
    TextView tvContent1;
    @BindView(R.id.tv_chatcontent)
    TextView tvContent2;
    @BindView(R.id.tv_chatcontent3)
    TextView tvContent3;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_userhead)
    ImageView ivUserhead;
    private float textsize1, textsize2, textsize3;
    private float textSizef;//縮放比例
    private int currentIndex;
    private boolean isClickable = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_textsizeshow);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        currentIndex = MyApplication.getMyInstance().getPreferencesHelper().getValueInt("currentIndex", 1);
        textSizef = 1 + currentIndex * 0.1f;
        textsize1 = tvContent1.getTextSize() / textSizef;
        textsize2 = tvContent2.getTextSize() / textSizef;
        textsize3 = tvContent3.getTextSize() / textSizef;
        fontSliderBar.setTickCount(6).setTickHeight(DisplayUtils.convertDip2Px(TextSizeShowActivity.this, 15)).setBarColor(Color.GRAY)
                .setTextColor(Color.BLACK).setTextPadding(DisplayUtils.convertDip2Px(TextSizeShowActivity.this, 10)).setTextSize(DisplayUtils.convertDip2Px(TextSizeShowActivity.this, 14))
                .setThumbRadius(DisplayUtils.convertDip2Px(TextSizeShowActivity.this, 10)).setThumbColorNormal(Color.GRAY).setThumbColorPressed(Color.GRAY)
                .setOnSliderBarChangeListener(new FontSliderBar.OnSliderBarChangeListener() {
                    @Override
                    public void onIndexChanged(FontSliderBar rangeBar, int index) {
                        if(index>5){
                            return;
                        }
                        index = index - 1;
                        float textSizef = 1 + index * 0.1f;
                        setTextSize(textSizef);
                    }
                }).setThumbIndex(currentIndex).withAnimation(false).applay();
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (fontSliderBar.getCurrentIndex() != currentIndex) {
                    if (isClickable) {
                        isClickable = false;
                        refresh();
                    }
                } else {
                    finish();
                }
            }
        });
    }

    private void setTextSize(float textSize) {
        //改變當前頁面的字型大小
        tvContent1.setTextSize(DisplayUtils.px2sp(TextSizeShowActivity.this, textsize1 * textSize));
        tvContent2.setTextSize(DisplayUtils.px2sp(TextSizeShowActivity.this, textsize2 * textSize));
        tvContent3.setTextSize(DisplayUtils.px2sp(TextSizeShowActivity.this, textsize3 * textSize));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (currentIndex != fontSliderBar.getCurrentIndex()) {
                if (isClickable) {
                    isClickable = false;
                    refresh();
                }
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void refresh() {
        //儲存標尺的下標
        MyApplication.getMyInstance().getPreferencesHelper().setValue("currentIndex", fontSliderBar.getCurrentIndex());
        //通知主頁面重啟
        RxBus.getInstance().post(MainActivity.class.getSimpleName(), new MessageSocket(99, null, null, null));
        //重啟mainActivity
        RxBus.getInstance().post(MainActivity.class.getSimpleName(), new MessageSocket(99, null, null, null));
//        showMyDialog();
        //2s後關閉  延遲執行任務 重啟完主頁
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                hideMyDialog();
                finish();
            }
        }, 2000);
    }


}

三.總結
不將就一個個修改,那麼久沉下心來分析,然後總結下,避免下次繼續踩坑。