简体   繁体   中英

Android TextView, autoLink=“all” showing all numbers as clickable

I have a Scrollview and I have the attribute android:clickable="true" and android:autoLink="all" .

I have a string for the ScrollView, and the emails, tel numbers etc, appear and are correctly clickable.

However, The string contains other numbers, such as Years, which also appear clickable and I don't want this; how can I stop this from happening?

Don't use autoLink="all" , use the ones you need .

android:autoLink="web|email|phone" will probably cover your use cases.

The clickable="true" on the ScrollView isn't needed for this; rather you should set the autoLink attribute on the TextViews themselves; perhaps extracting a style if you have other common properties.


Add the new Linkify class to your project. From a place that you have access to the TextView (eg the Activity):

TextView myTextView = // get a reference to your textview
int mask = Linkify.ALL;
Linkify.addLinks(myTextView, mask);

The addLinks(TextView, int) method is static, so you can use it without creating an instance of Linkify . The return value ( boolean ) indicates whether something was linkified, but you probably don't need this information, so we don't bother with it.

You'll need to ensure that you don't put the autoLink attribute on the TextViews , otherwise the setText(...) implementations will still linkify years (unless you completely override the setText(...) implementations without calling super.setText(...) )


For extra brownie points, you can create a subclass of TextView which will do the linkify for you when you set text on it:

public class AutoLinkifyTextView extends TextView {

    public AutoLinkifyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AutoLinkifyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setText(String text) {
        super.setText(text);
        parseLinks();
    }

    @Override
    public void setText(int stringRes) {
        super.setText(stringRes);
        parseLinks();
    }

    private void parseLinks() {
        Linkify.addLinks(this, Linkify.ALL);
    }

}

For top marks of course, you'd read the attributes from the attrs and use the correct mask from the XML attributes, but I'd prefer to get rid of that option and do it here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM