Android開發-TextViev XML屬性(一)

一任天然發表於2016-07-07

Android開發-TextViev(一)

TextView是Android中最常用的控制元件之一,大部分時候大家只使用了一些簡單的功能。比如:顯示一個字串,顯示一個HTML片段等。我們一起來詳細瞭解一下TextView。

ConstantValueDescription
none0x00 Match no patterns (default).
web0x01 Match Web URLs.
email0x02 Match email addresses.
phone0x04 Match phone numbers.
map0x08 Match map addresses.
all0x0f Match all patterns (equivalent to web|email|phone|map).

xml片段

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:autoLink="phone"
        android:text="13888888888" />

執行效果

Android開發-TextViev XML屬性(一)

Tips

點選電話號碼後跳轉到撥號頁面,如果不是電話號碼則無效。

原始碼分析

    /**
     *  掃描提供的常量,新增對應的link。(這裡以phone為例)
     */
    public static final boolean addLinks(Spannable text, int mask) {
        if (mask == 0) {
            return false;
        }

        URLSpan[] old = text.getSpans(0, text.length(), URLSpan.class);

        for (int i = old.length - 1; i >= 0; i--) {
            text.removeSpan(old[i]);
        }

        ArrayList<LinkSpec> links = new ArrayList<LinkSpec>();

        // 這裡只保留了PHONE型別

        if ((mask & PHONE_NUMBERS) != 0) {
            gatherTelLinks(links, text);
        }

        pruneOverlaps(links);

        if (links.size() == 0) {
            return false;
        }

        for (LinkSpec link: links) {
            applyLink(link.url, link.start, link.end, text);
        }

        return true;
    }
    /**
     * 在URL中增加"tel:",點選後跳轉到撥打電話頁面
     */
    private static final void gatherTelLinks(ArrayList<LinkSpec> links, Spannable s) {
        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        Iterable<PhoneNumberMatch> matches = phoneUtil.findNumbers(s.toString(),
                Locale.getDefault().getCountry(), Leniency.POSSIBLE, Long.MAX_VALUE);
        for (PhoneNumberMatch match : matches) {
            LinkSpec spec = new LinkSpec();
            spec.url = "tel:" + PhoneNumberUtils.normalizeNumber(match.rawString());
            spec.start = match.start();
            spec.end = match.end();
            links.add(spec);
        }
    }

android:autoText

從API3以後不建議使用android:autoText,使用inputType替代。

android:breakStrategy

ConstantValueDescription
simple0 Line breaking uses simple strategy.
high_quality1 Line breaking uses high-quality strategy, including hyphenation.
balanced2 Line breaking strategy balances line lengths.

android:bufferType

ConstantValueDescription
normal0 Can return any CharSequence, possibly a Spanned one if the source text was Spanned.
spannable1 Can only return Spannable.
editable2 Can only return Spannable and Editable.

待續···

相關文章