老司机带你重构Android的v4包的部分源码

版权声明:本文为博主原创文章,未经博主允许不得转载。//www.greatytc.com/p/a08d754944c4

转载请标明出处:
//www.greatytc.com/p/a08d754944c4
本文出自 AWeiLoveAndroid的博客


【前言】过年回家忙着干活,忙着给亲戚的孩子发红包,好累,忙里偷闲打开studio看了一下v4包,之前看过几个类,这次是每个类都看了一下,原来Android的v4包的源码也有一些是写的不是那么友好的,还有很多改善空间。

下面就拿其中的android.support.v4.text这个包里面的 TextUtilsCompatTextUtilsCompatJellybeanMr1 这两个类来做一个具体讲解。

本文源码同步发布在github,详情请点击 https://github.com/AweiLoveAndroid/refactor-android-support-v4

一、首先看一下Androidv4包下面的 TextUtilsCompatTextUtilsCompatJellybeanMr1 源码:

(一)TextUtilsCompat 源码:
public final class TextUtilsCompat {
    private static class TextUtilsCompatImpl {
        TextUtilsCompatImpl() {
        }

        @NonNull
        public String htmlEncode(@NonNull String s) {
            StringBuilder sb = new StringBuilder();
            char c;
            for (int i = 0; i < s.length(); i++) {
                c = s.charAt(i);
                switch (c) {
                    case '<':
                        sb.append("&lt;"); //$NON-NLS-1$
                        break;
                    case '>':
                        sb.append("&gt;"); //$NON-NLS-1$
                        break;
                    case '&':
                        sb.append("&amp;"); //$NON-NLS-1$
                        break;
                    case '\'':
                        //http://www.w3.org/TR/xhtml1
                        // The named character reference &apos; (the apostrophe, U+0027) was
                        // introduced in XML 1.0 but does not appear in HTML. Authors should
                        // therefore use &#39; instead of &apos; to work as expected in HTML 4
                        // user agents.
                        sb.append("&#39;"); //$NON-NLS-1$
                        break;
                    case '"':
                        sb.append("&quot;"); //$NON-NLS-1$
                        break;
                    default:
                        sb.append(c);
                }
            }
            return sb.toString();
        }

        public int getLayoutDirectionFromLocale(@Nullable Locale locale) {
            if (locale != null && !locale.equals(ROOT)) {
                final String scriptSubtag = ICUCompat.maximizeAndGetScript(locale);
                if (scriptSubtag == null) return getLayoutDirectionFromFirstChar(locale);

                // This is intentionally limited to Arabic and Hebrew scripts, since older
                // versions of Android platform only considered those scripts to be right-to-left.
                if (scriptSubtag.equalsIgnoreCase(ARAB_SCRIPT_SUBTAG) ||
                        scriptSubtag.equalsIgnoreCase(HEBR_SCRIPT_SUBTAG)) {
                    return ViewCompat.LAYOUT_DIRECTION_RTL;
                }
            }
            return ViewCompat.LAYOUT_DIRECTION_LTR;
        }

        /**
         * Fallback algorithm to detect the locale direction. Rely on the first char of the
         * localized locale name. This will not work if the localized locale name is in English
         * (this is the case for ICU 4.4 and "Urdu" script)
         *
         * @param locale
         * @return the layout direction. This may be one of:
         * {@link ViewCompat#LAYOUT_DIRECTION_LTR} or
         * {@link ViewCompat#LAYOUT_DIRECTION_RTL}.
         *
         * Be careful: this code will need to be updated when vertical scripts will be supported
         */
        private static int getLayoutDirectionFromFirstChar(@NonNull Locale locale) {
            switch(Character.getDirectionality(locale.getDisplayName(locale).charAt(0))) {
                case Character.DIRECTIONALITY_RIGHT_TO_LEFT:
                case Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC:
                    return ViewCompat.LAYOUT_DIRECTION_RTL;

                case Character.DIRECTIONALITY_LEFT_TO_RIGHT:
                default:
                    return ViewCompat.LAYOUT_DIRECTION_LTR;
            }
        }
    }

    private static class TextUtilsCompatJellybeanMr1Impl extends TextUtilsCompatImpl {
        TextUtilsCompatJellybeanMr1Impl() {
        }

        @Override
        @NonNull
        public String htmlEncode(@NonNull String s) {
            return TextUtilsCompatJellybeanMr1.htmlEncode(s);
        }

        @Override
        public int getLayoutDirectionFromLocale(@Nullable Locale locale) {
            return TextUtilsCompatJellybeanMr1.getLayoutDirectionFromLocale(locale);
        }
    }

    private static final TextUtilsCompatImpl IMPL;
    static {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 17) { // JellyBean MR1
            IMPL = new TextUtilsCompatJellybeanMr1Impl();
        } else {
            IMPL = new TextUtilsCompatImpl();
        }
    }

    /**
     * Html-encode the string.
     * @param s the string to be encoded
     * @return the encoded string
     */
    @NonNull
    public static String htmlEncode(@NonNull String s) {
        return IMPL.htmlEncode(s);
    }

    /**
     * Return the layout direction for a given Locale
     *
     * @param locale the Locale for which we want the layout direction. Can be null.
     * @return the layout direction. This may be one of:
     * {@link ViewCompat#LAYOUT_DIRECTION_LTR} or
     * {@link ViewCompat#LAYOUT_DIRECTION_RTL}.
     *
     * Be careful: this code will need to be updated when vertical scripts will be supported
     */
    public static int getLayoutDirectionFromLocale(@Nullable Locale locale) {
        return IMPL.getLayoutDirectionFromLocale(locale);
    }

    public static final Locale ROOT = new Locale("", "");

    static String ARAB_SCRIPT_SUBTAG = "Arab";
    static String HEBR_SCRIPT_SUBTAG = "Hebr";

    private TextUtilsCompat() {}
}
(二)TextUtilsCompatJellybeanMr1 源码:
/**
 * Jellybean MR1 - specific TextUtils API access.
 */
@RequiresApi(17)
@TargetApi(17)
class TextUtilsCompatJellybeanMr1 {
    @NonNull
    public static String htmlEncode(@NonNull String s) {
        return TextUtils.htmlEncode(s);
    }

    public static int getLayoutDirectionFromLocale(@Nullable Locale locale) {
        return TextUtils.getLayoutDirectionFromLocale(locale);
    }
}

二、分析一下以上源码的一些需要改进的问题(仅个人理解,如有不同意见,欢迎提出):

通过以上源码来看,看起来确实有点不是很舒服。

(一)排列顺序有点乱,我格式化了一下,如下,看的稍微清楚了一些:
/**
 * 格式化之后的TextUtilsCompat类
 */
public class TextUtilsCompat {

    private static final TextUtilsCompatImpl IMPL;

    public static final Locale ROOT = new Locale("", "");

    static String ARAB_SCRIPT_SUBTAG = "Arab";
    static String HEBR_SCRIPT_SUBTAG = "Hebr";

    private TextUtilsCompat() {}

    static {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 17) { // JellyBean MR1
            IMPL = new TextUtilsCompatJellybeanMr1Impl();
        } else {
            IMPL = new TextUtilsCompatImpl();
        }
    }

    /**
     * Html-encode the string.
     * @param s the string to be encoded
     * @return the encoded string
     */
    @NonNull
    public static String htmlEncode(@NonNull String s) {
        return IMPL.htmlEncode(s);
    }

    /**
     * Return the layout direction for a given Locale
     *
     * @param locale the Locale for which we want the layout direction. Can be null.
     * @return the layout direction. This may be one of:
     * {@link ViewCompat#LAYOUT_DIRECTION_LTR} or
     * {@link ViewCompat#LAYOUT_DIRECTION_RTL}.
     *
     * Be careful: this code will need to be updated when vertical scripts will be supported
     */
    public static int getLayoutDirectionFromLocale(@Nullable Locale locale) {
        return IMPL.getLayoutDirectionFromLocale(locale);
    }


    private static class TextUtilsCompatImpl {

        TextUtilsCompatImpl() {}

        @NonNull
        public String htmlEncode(@NonNull String s) {
            StringBuilder sb = new StringBuilder();
            char c;
            for (int i = 0; i < s.length(); i++) {
                c = s.charAt(i);
                switch (c) {
                    case '<':
                        sb.append("&lt;"); //$NON-NLS-1$
                        break;
                    case '>':
                        sb.append("&gt;"); //$NON-NLS-1$
                        break;
                    case '&':
                        sb.append("&amp;"); //$NON-NLS-1$
                        break;
                    case '\'':
                        //http://www.w3.org/TR/xhtml1
                        // The named character reference &apos; (the apostrophe, U+0027) was
                        // introduced in XML 1.0 but does not appear in HTML. Authors should
                        // therefore use &#39; instead of &apos; to work as expected in HTML 4
                        // user agents.
                        sb.append("&#39;"); //$NON-NLS-1$
                        break;
                    case '"':
                        sb.append("&quot;"); //$NON-NLS-1$
                        break;
                    default:
                        sb.append(c);
                }
            }
            return sb.toString();
        }

        public int getLayoutDirectionFromLocale(@Nullable Locale locale) {
            if (locale != null && !locale.equals(ROOT)) {
                final String scriptSubtag = ICUCompat.maximizeAndGetScript(locale);
                if (scriptSubtag == null) {
                    return getLayoutDirectionFromFirstChar(locale);
                }

                // This is intentionally limited to Arabic and Hebrew scripts, since older
                // versions of Android platform only considered those scripts to be right-to-left.
                if (scriptSubtag.equalsIgnoreCase(ARAB_SCRIPT_SUBTAG) ||
                        scriptSubtag.equalsIgnoreCase(HEBR_SCRIPT_SUBTAG)) {
                    return ViewCompat.LAYOUT_DIRECTION_RTL;
                }
            }
            return ViewCompat.LAYOUT_DIRECTION_LTR;
        }

        /**
         * Fallback algorithm to detect the locale direction. Rely on the first char of the
         * localized locale name. This will not work if the localized locale name is in English
         * (this is the case for ICU 4.4 and "Urdu" script)
         *
         * @param locale
         * @return the layout direction. This may be one of:
         * {@link ViewCompat#LAYOUT_DIRECTION_LTR} or
         * {@link ViewCompat#LAYOUT_DIRECTION_RTL}.
         *
         * Be careful: this code will need to be updated when vertical scripts will be supported
         */
        private static int getLayoutDirectionFromFirstChar(@NonNull Locale locale) {
            switch(Character.getDirectionality(locale.getDisplayName(locale).charAt(0))) {
                case Character.DIRECTIONALITY_RIGHT_TO_LEFT:
                case Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC:
                    return ViewCompat.LAYOUT_DIRECTION_RTL;

                case Character.DIRECTIONALITY_LEFT_TO_RIGHT:
                default:
                    return ViewCompat.LAYOUT_DIRECTION_LTR;
            }
        }
    }

    private static class TextUtilsCompatJellybeanMr1Impl extends TextUtilsCompatImpl {
        TextUtilsCompatJellybeanMr1Impl() {
        }

        @Override
        @NonNull
        public String htmlEncode(@NonNull String s) {
            return TextUtilsCompatJellybeanMr1.htmlEncode(s);
        }

        @Override
        public int getLayoutDirectionFromLocale(@Nullable Locale locale) {
            return TextUtilsCompatJellybeanMr1.getLayoutDirectionFromLocale(locale);
        }
    }

}
(二)TextUtilsCompat 这个类里面有两个内部类,一个是TextUtilsCompatImpl,一个是TextUtilsCompatJellybeanMr1Impl,TextUtilsCompatJellybeanMr1Impl是继承自TextUtilsCompatImpl的。
(三)从静态代码块看出,api 大于17 使用 new TextUtilsCompatJellybeanMr1Impl(); api小于17 使用TextUtilsCompatImpl。TextUtilsCompat,TextUtilsCompatImpl和TextUtilsCompatJellybeanMr1Impl里面都有 htmlEncode 方法和 getLayoutDirectionFromLocale 方法。

静态代码块里面通过TextUtilsCompatImpl IMPL这个常量来判断,当api大于17用TextUtilsCompatJellybeanMr1Impl,否则用TextUtilsCompatImpl,然后htmlEncode方法调用了对应内部类里面的htmlEncode方法,getLayoutDirectionFromLocale调用了对应内部类里面的getLayoutDirectionFromLocale方法。

(四)TextUtilsCompatImpl和TextUtilsCompatJellybeanMr1Impl里面都有 htmlEncode 方法和 getLayoutDirectionFromLocale 方法,看看它们的区别。

(1)TextUtilsCompatJellybeanMr1Impl这个内部类的方法解析:

  • htmlEncode(@NonNull String s) 方法 返回的是:
TextUtilsCompatJellybeanMr1.htmlEncode(s); ==> 调用了TextUtils.htmlEncode(s);
  • getLayoutDirectionFromLocale(@Nullable Locale locale) 方法返回的是:
TextUtilsCompatJellybeanMr1.getLayoutDirectionFromLocale(locale); ==> 调用了TextUtils.getLayoutDirectionFromLocale(locale);

(2)TextUtilsCompatImpl这个内部类的方法解析:

  • htmlEncode(@NonNull String s) 方法 返回的是:
在这个方法内部写了一遍,跟TextUtils.htmlEncode(s);方法里面的一模一样。
  • getLayoutDirectionFromLocale(@Nullable Locale locale) 方法返回的是:
重新写了一遍,这个方法是真正有所区别的地方。

三、根据我做过项目用到的MVP的开发模式,我把共同的htmlEncode方法和getLayoutDirectionFromLocale方法抽取出一个接口,然后分别用两个实现类去实现接口,然后用TextUtilsCompat这个类去判断调用哪个实现类的方法,这样看起来更直观一些。具体步骤如下:

(一)抽取公共接口ITextUtilsCompat
/**
 * 抽取公用的接口
 */
public interface ITextUtilsCompat {

    /**
     * Html-encode the string.
     * @param s the string to be encoded
     * @return the encoded string
     */
    public String htmlEncode(@NonNull String s);

    /**
     * Return the layout direction for a given Locale
     *
     * @param locale the Locale for which we want the layout direction. Can be null.
     * @return the layout direction. This may be one of:
     * {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_LTR} or
     * {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_RTL}.
     *
     * Be careful: this code will need to be updated when vertical scripts will be supported
     */
    public int getLayoutDirectionFromLocale(@Nullable Locale locale);
}
(二)写一个TextUtilsCompatJellybeanMr1实现ITextUtilsCompat 接口,然后把之前TextUtilsCompatJellybeanMr1类里面的复制过来,具体如下:
/**
 * 兼容Android 17+ 版本
 * Jellybean MR1 - specific TextUtils API access.
 */
@RequiresApi(17)
@TargetApi(17)
class TextUtilsCompatJellybeanMr1 implements ITextUtilsCompat{

    @Override
    @NonNull
    public String htmlEncode(@NonNull String s) {
        return TextUtils.htmlEncode(s);
    }

    @Override
    public int getLayoutDirectionFromLocale(@Nullable Locale locale) {
        return TextUtils.getLayoutDirectionFromLocale(locale);
    }
}
(三)写一个类TextUtilsCompatImpl实现ITextUtilsCompat 接口,然后把之前TextUtilsCompat类里面的有关代码复制过来,具体如下:
/**
 * Android 17以下版本使用这个类
 */
class TextUtilsCompatImpl implements ITextUtilsCompat{

    public static final Locale ROOT = new Locale("", "");

    static String ARAB_SCRIPT_SUBTAG = "Arab";
    static String HEBR_SCRIPT_SUBTAG = "Hebr";


    @Override
    @NonNull
    public String htmlEncode(@NonNull String s) {
        StringBuilder sb = new StringBuilder();
        char c;
        for (int i = 0; i < s.length(); i++) {
            c = s.charAt(i);
            switch (c) {
                case '<':
                    sb.append("&lt;"); //$NON-NLS-1$
                    break;
                case '>':
                    sb.append("&gt;"); //$NON-NLS-1$
                    break;
                case '&':
                    sb.append("&amp;"); //$NON-NLS-1$
                    break;
                case '\'':
                    //http://www.w3.org/TR/xhtml1
                    // The named character reference &apos; (the apostrophe, U+0027) was
                    // introduced in XML 1.0 but does not appear in HTML. Authors should
                    // therefore use &#39; instead of &apos; to work as expected in HTML 4
                    // user agents.
                    sb.append("&#39;"); //$NON-NLS-1$
                    break;
                case '"':
                    sb.append("&quot;"); //$NON-NLS-1$
                    break;
                default:
                    sb.append(c);
            }
        }
        return sb.toString();
    }


    @Override
    public int getLayoutDirectionFromLocale(@Nullable Locale locale) {
        if (locale != null && !locale.equals(ROOT)) {
            final String scriptSubtag = ICUCompat.maximizeAndGetScript(locale);
            if (scriptSubtag == null) {
                return getLayoutDirectionFromFirstChar(locale);
            }

            // This is intentionally limited to Arabic and Hebrew scripts, since older
            // versions of Android platform only considered those scripts to be right-to-left.
            if (scriptSubtag.equalsIgnoreCase(ARAB_SCRIPT_SUBTAG) ||
                    scriptSubtag.equalsIgnoreCase(HEBR_SCRIPT_SUBTAG)) {
                return ViewCompat.LAYOUT_DIRECTION_RTL;
            }
        }
        return ViewCompat.LAYOUT_DIRECTION_LTR;
    }

    /**
     * Fallback algorithm to detect the locale direction. Rely on the first char of the
     * localized locale name. This will not work if the localized locale name is in English
     * (this is the case for ICU 4.4 and "Urdu" script)
     *
     * @param locale
     * @return the layout direction. This may be one of:
     * {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_LTR} or
     * {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_RTL}.
     *
     * Be careful: this code will need to be updated when vertical scripts will be supported
     */
    private static int getLayoutDirectionFromFirstChar(@NonNull Locale locale) {
        switch(Character.getDirectionality(locale.getDisplayName(locale).charAt(0))) {
            case Character.DIRECTIONALITY_RIGHT_TO_LEFT:
            case Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC:
                return ViewCompat.LAYOUT_DIRECTION_RTL;

            case Character.DIRECTIONALITY_LEFT_TO_RIGHT:
            default:
                return ViewCompat.LAYOUT_DIRECTION_LTR;
        }
    }
}
(四)封装TextUtilsCompat给调用者使用,具体如下:
/**
 * v4包下面的TextUtilsCompat的简单优化
 * 这里使用的是策略模式,根据不同api版本调用不同的接口实现类
 * 这样写更好维护。
 */
public final class TextUtilsCompat {

    private static final ITextUtilsCompat IMPL;

    private TextUtilsCompat() {}

    static {
        final int version = Build.VERSION.SDK_INT;
        // JellyBean MR1 大于等于17
        if (version >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            IMPL = new TextUtilsCompatJellybeanMr1();
        } else {
            IMPL = new TextUtilsCompatImpl();
        }
    }

    /**
     * Html-encode the string.
     * @param s the string to be encoded
     * @return the encoded string
     */
    @NonNull
    public static String htmlEncode(@NonNull String s) {
        return IMPL.htmlEncode(s);
    }

    /**
     * Return the layout direction for a given Locale
     *
     * @param locale the Locale for which we want the layout direction. Can be null.
     * @return the layout direction. This may be one of:
     * {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_LTR} or
     * {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_RTL}.
     *
     * Be careful: this code will need to be updated when vertical scripts will be supported
     */
    public static int getLayoutDirectionFromLocale(@Nullable Locale locale) {
        return IMPL.getLayoutDirectionFromLocale(locale);
    }
    
}

到此,TextUtilsCompat 这个类就封装完了。看完之后是不是很清爽?其实还有很多类似的类都可以根据类似的方式做一下改进的。源码不是完美的,只要掌握以上示例代码的思想还是很容易的让代码更好理解,更简洁清晰的。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,772评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,458评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,610评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,640评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,657评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,590评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,962评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,631评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,870评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,611评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,704评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,386评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,969评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,944评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,179评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,742评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,440评论 2 342

推荐阅读更多精彩内容