Search code examples
androidandroid-edittexthashtaglinkify

Linkify in EditText to Detect Hashtags


I am using Linkify to detect hashtags in a TextView and it's working fine but I want to implement it inside an EditText control.

This is the way that I use Linkify in TextView:

Pattern tagMatcher = Pattern.compile(("#([ء-يA-Za-z0-9_-]+)"));
String newActivityURL = "content://com.hashtag.jojo/";

Pattern urlPattern = Patterns.WEB_URL;

TransformFilter transformFilter = new TransformFilter() {
    // skip the first character to filter out '@'
    public String transformUrl(final Matcher match, String url) {
        return match.group(0);
    }
};
Linkify.addLinks(TextView, Linkify.ALL);
Linkify.addLinks(TextView, tagMatcher,newActivityURL, null,transformFilter);

How do I apply this to an EditText?


Solution

  • Just do what you do with EditText instead of TextView, because EditText extends from TextView. It must be work fine.

    Little example:

    EditText editText1 = (EditText) findViewById(R.id.editText1);
    editText1.setText("http://http://www.dzone.com/");
    Linkify.addLinks(editText1 , Linkify.WEB_URLS);
    

    If you want check it in real-time just do something like that:

    editText1.addTextChangedListener(new TextWatcher() {
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Linkify.addLinks(editText1 , Linkify.WEB_URLS);
        }
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
    
        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    

    updated

    final TransformFilter filter = new TransformFilter() {
        public final String transformUrl(final Matcher match, String url) {
            return match.group();
        }
    };
    
    final Pattern hashtagPattern = Pattern.compile("#([ء-يA-Za-z0-9_-]+)");
    final String hashtagScheme = "content://com.hashtag.jojo/";
    
    final Pattern urlPattern = Patterns.WEB_URL;
    
    editText1.addTextChangedListener(new TextWatcher() {
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            System.out.println(count);
        }
    
        @Override
        public void afterTextChanged(Editable s) {
            Linkify.addLinks(s, hashtagPattern, hashtagScheme, null, filter);
            Linkify.addLinks(s, urlPattern, null, null, filter);
        }
    });