解決系統改變字體大小的時候導致的界面佈局混亂的問題

轉自:http://www.android100.org/html/201401/13/5330.html

從android4.0起系統設置的”顯示“提供設置字體大小的選項。這個設置直接會影響到所有sp爲單位的字體適配,所以很多app在設置了系統字體後瞬間變得面目全非。下面是解決方案

 
Resources res = getResources();
Configuration config=new Configuration();
config.setToDefaults();
res.updateConfiguration(config,res.getDisplayMetrics() );
 
雖然google推薦使用sp作爲字體的單位,但實際的開發過程中通常是根據UIUE的設計稿來換算 sp(px換算sp)。而sp即使在同一種密度下其值也不盡相同。比如在240dpi的設備,如果是480x800分辨率這個值通常是1.5倍 (scaledDensity=1.5),如果是480xZ(z>800)那麼這個值有可能大於1.5。這無疑給設備的適配帶來更多的困難和陷阱。所以個人通常建議使用dpi來作爲字體的單位

對於個別app不需要根據系統字體的大小來改變的,可以在activity基類(app中所有的activity都應該有繼承於我們自己定義的一個activity類)中加上以下code:
例如:Contacts中需要在com.android.contacts.activities.TransactionSafeActivity加入以下code
    @Override
    public Resources getResources() {
        Resources res = super.getResources();  
        Configuration config=new Configuration();  
        config.setToDefaults();  
        res.updateConfiguration(config,res.getDisplayMetrics() );
        return res;
    }
如果app中只是個別界面不需要,可改造下此方法
 @Override
    public Resources getResources() {
        if(isNeedSystemResConfig()){
            return super.getResources();
        }else{
            Resources res = super.getResources();  
            Configuration config=new Configuration(); 
            config.setToDefaults(); 
            res.updateConfiguration(config,res.getDisplayMetrics() );
            return res;
        }
    }
    // 默認返回true,使用系統資源,如果個別界面不需要,在這些activity中Override this method ,then return false;
    protected boolean isNeedSystemResConfig() {
        return true;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章