Android 動態修改資源文件方案

背景:產品上線後,經常有用戶或者產品反饋語言翻譯有誤,導致app可能因爲翻譯的問題,重複升級打包,這樣大大增加工作量.

app中展示的靜態文案大體分兩種
第一種是使用strings.xml靜態配置到app中,跟隨app打包;
第二種是服務端通過接口下發,在顯示字符串的時候使用服務器下發的內容.但是之前內容很多都是寫在了xml或者settext(),整體改起來工作量就很大.

現在針對第二種方案處理方式,一共有2中方案.
1.獲取、並更改xml中的文案,我們可以嘗試使用繼承TextView並替換的方式來實現,在子類的構造方法中可以拿到attrs,進而拿到對應的id,
繼承TextView可行,但是存量的代碼改起來成本太大,不是首選方案,所以這裏不得不提到LayoutInflater中的一個神奇的方法setFactory/setFactory2,這個方法可以設置一個Factory,在View被inflate之前,hook view inflate的邏輯,並可以做一些羞羞的事情。不過要注意的是,這個方法只適用於inflate的view,new TextView()這種是沒有辦法攔截到的。直接上代碼
首先在BaseActivity的oncreate()方法中增加setFactory2();需要在
super.onCreate(savedInstanceState)之前

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //GTLangUtil.getInstance().changLanguage(this);
        setAttachBaseContext(this);
        setFactory2();
        super.onCreate(savedInstanceState);
}
    /**
     * des: 通過攔截所有的textview,獲取對應的key
     * author:lucas
     * date:2022/5/19 3:28 下午
     */
    private void setFactory2() {
        LayoutInflaterCompat.setFactory2(getLayoutInflater(), new LayoutInflater.Factory2() {
            @Override
            public View onCreateView(@Nullable View parent, @NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs) {
                LayoutInflater inflater = LayoutInflater.from(context);
                AppCompatActivity activity = null;
                if (parent == null) {
                    if (context instanceof AppCompatActivity) {
                        activity = ((AppCompatActivity)context);
                    }
                } else if (parent.getContext() instanceof AppCompatActivity) {
                    activity = (AppCompatActivity) parent.getContext();
                }
                if (activity == null) {
                    return null;
                }
                AppCompatDelegate delegate = activity.getDelegate();
                int[] set = {
                        android.R.attr.text        // idx 0
                };

                // 不需要recycler,後面會在創建view時recycle的
                @SuppressLint("Recycle")
                TypedArray a = context.obtainStyledAttributes(attrs, set);
                View view = delegate.createView(parent, name, context, attrs);
                if (view == null && name.indexOf('.') > 0) { //表明是自定義View
                    try {
                        view = inflater.createView(name, null, attrs);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }

                if (view instanceof TextView) {
                    int resourceId = a.getResourceId(0, 0);
                    if (resourceId != 0) {
//                       這裏獲取了key,通過key就可以定位到服務器的內容了
//                        String n = context.getResources().getResourceEntryName(resourceId);
                        ((TextView) view).setText(AppMain.getAppString(resourceId));

                    }
                }

                return view;
            }

            @Override
            public View onCreateView(@NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs) {
                return null;
            }
        });
    }

第二種方案就是更加簡單
獲取、並更改setText(int resId)的文案
通過閱讀源碼發現,TextView#setText(int resId)這個方法有final修飾,且其爲Android SDK的代碼,我們無法觸及,所以根本無法hook這個method。那就只剩嘗試能不能hook Activity#getResoures()這個方法了。
幸運的是,Activity#getResoures()是public且沒有被final修飾的, 所以我們可以在BaseActivity中重寫該方法,使用一個Resouces的裝飾類來改變getResoures().getString(int resId)的return值。

  /**
     * 重寫 getResource 方法FakeResourcesWrapper()
     */
    @Override
    public Resources getResources() {//禁止app字體大小跟隨系統字體大小調節
        Resources resources = super.getResources();
        if (resources != null && resources.getConfiguration().fontScale != 1.0f) {
            android.content.res.Configuration configuration = resources.getConfiguration();
            configuration.fontScale = 1.0f;
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        }
        return new FakeResourcesWrapper(resources);
    }

    /**
     * des: 裝飾者模式 重寫Resources獲取textview的key
     * author:lucas 
     * date:2022/5/19 3:27 下午
     */
    public class FakeResourcesWrapper extends Resources {

        private Resources mResources;

        private FakeResourcesWrapper(AssetManager assets, DisplayMetrics metrics, Configuration config) {
            super(assets, metrics, config);
        }

        public FakeResourcesWrapper(Resources resources) {
            super(resources.getAssets(), resources.getDisplayMetrics(), resources.getConfiguration());
            mResources = resources;
        }

        // getText(int id); getString(int id); getString(int id, Object... formatArgs);getText(int id, CharSequence def)都需要被重寫,都返回resourceEntryName而非value
        @NonNull
        @Override
        public CharSequence getText(int id) throws NotFoundException {
            return super.getResourceEntryName(id);
        }


        //...... 其他所有的public方法都需要被重寫,使用被修飾的resouces的方法
        @Override
        public float getDimension(int id) throws NotFoundException {
       //這裏獲取了key,通過key就可以定位到服務器的內容了
     //String n = context.getResources().getResourceEntryName(resourceId);
            return mResources.getDimension(id);
        }
        //......

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章