Simplest guidance to implement Hashtag Mentions in Android Mobile App

Hashtag Mentions are used by all major social media platforms today. It’s a convenient tool for filtering relevant content. Today, with hashtags Mentions so common, not only people already use them on each social media platform, but they’re also starting to expect these feature in other apps.

Hashtags Mentions

mention (also known as @replies or tagging, not to be confused with metadata tags or hashtags) is a means by which a blog post references or links to a user’s profile. This may be done as a matter of getting the attention of (or drawing attention to) another user of a social networking or blogging service, as a matter of replying to the other user’s post, or as a matter of “tagging” a user in a post

Hashtags are mostly used in unmoderated, ad hoc discussion forums; any combination of characters led by a hash symbol is a hashtag, and any hashtag, if promoted by enough individuals, can “trend” and attract more individual users to a discussion. On Twitter, when a hashtag becomes extremely popular, it will appear in the “Trending Topics” area of a user’s homepage.

Steps to Implement Hashtag Mentions in Android Mobile App

Step 1:

Add the Sdk that will help  for the autocomplete list

//to add hastag n mention
implementation 'com.otaliastudios:autocomplete:1.1.0'

Step 2:

This method will help to add the hashtag values that we want to add in the list.

private void setupHashAutocomplete() {
        float elevation = 6f;
        List<String> hash = new ArrayList<>();
        hash.add("hash");
        hash.add("happy");
        hash.add("enjoy");
        hash.add("sad");
        hash.add("party");
        hash.add("bash");
        hash.add("color");
        hash.add("define");
        Drawable backgroundDrawable = new ColorDrawable(Color.WHITE);
        AutocompletePolicy hashpolicy = new CharPolicy('#'); // Look for #hash
        AutocompletePresenter<String> hashpresenter = new HashPresenter(this,hash);
        AutocompleteCallback<String> hashcallback = new AutocompleteCallback<String>() {
            @Override
            public boolean onPopupItemClicked(Editable editable, String item) {
                // Replace query text with the full name.
                int[] range = CharPolicy.getQueryRange(editable);
                if (range == null) return false;
                int start = range[0];
                int end = range[1];
                String replacement = item;
                editable.replace(start, end, replacement);
                // This is better done with regexes and a TextWatcher, due to what happens when
                // the user clears some parts of the text. Up to you.
//                editable.setSpan(new StyleSpan(Typeface.BOLD), start, start+replacement.length(),
//                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                Log.d(TAG,"AutoComplete text value---->"+editable.toString());
                return true;
            }
            public void onPopupVisibilityChanged(boolean shown) {


            }
        };

        hashAutocomplete = Autocomplete.<String>on(postEditText)
                .with(elevation)
                .with(backgroundDrawable)
                .with(hashpolicy)
                .with(hashpresenter)
                .with(hashcallback)
                .build();
    }

Step 3:

This method will help to add friend list with the @ to mention the friends.

private void setupMentionsAutocomplete(List<User> friends) {
        mentionsUser = new JsonObject();
        float elevation = 6f;
        Drawable backgroundDrawable = new ColorDrawable(Color.WHITE);
        AutocompletePolicy policy = new CharPolicy('@'); // Look for @mentions
        AutocompletePresenter<User> presenter = new UserPresenter(this,friends);

        AutocompleteCallback<User> callback = new AutocompleteCallback<User>() {
            @Override
            public boolean onPopupItemClicked(Editable editable, User item) {
                // Replace query text with the full name.
                int[] range = CharPolicy.getQueryRange(editable);
                if (range == null) return false;
                int start = range[0];
                int end = range[1];
                String replacement = item.getUsername();
                editable.replace(start, end, replacement);
                // This is better done with regexes and a TextWatcher, due to what happens when
                // the user clears some parts of the text. Up to you.
                mentionsUser.addProperty("user_"+item.getUserId(),item.getUsername());
                return true;
            }
            public void onPopupVisibilityChanged(boolean shown) {}
        };

        mentionsAutocomplete = Autocomplete.<User>on(postEditText)
                .with(elevation)
                .with(backgroundDrawable)
                .with(policy)
                .with(presenter)
                .with(callback)
                .build();
    }

Step 4 & 5:

This method will help to set the Hashtag and Mentioned user with different colors. This method will also handle the clickable event in the Hastag and Mentioned user.

//Method for HashMap and Mentions
    private void setSpan(String text, final List<User> user, final Fragment feedsFragment) {
        //String test = "There is a package waiting for you to pick up from #surat to #mumbai";
        SpannableString spannable = new SpannableString(text);
        final Matcher Hashmatcher = Pattern.compile("#s*(w+)").matcher(text);
        final Matcher mention = Pattern.compile("@s*(w+)").matcher(text);
        while (Hashmatcher.find()) {
            final String city = Hashmatcher.group(1);
            ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(View textView) {
                    //Your Redirect Activity or Fragment
                }
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setUnderlineText(false);
                    //ds.setColor(mcontext.getResources().getColor(R.color.themeDarkColor));
                    ds.setColor(Color.BLACK);
                }
            };
            int cityIndex = text.indexOf(city) - 1;
            spannable.setSpan(clickableSpan, cityIndex, cityIndex + city.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        while (mention.find()) {
            final String city = mention.group(1);
            ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(View textView) {
                     //Your Redirect Activity or Fragment
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setUnderlineText(false);
                    ds.setColor(Color.BLACK);
                    ds.setFakeBoldText(true);
                }
            };
            int cityIndex = text.indexOf(city) - 1;
            spannable.setSpan(clickableSpan, cityIndex, cityIndex + city.length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if(user.size()>0) {
            for (int i = 0; i < user.size(); i++) {
                if (text.contains(user.get(i).getDisplayName())) {
                    //Log.d(Constants.TAG,"FeedTitle contains user-->"+tagUser.get(i).getDisplayName());
                    int startIndex = text.indexOf(user.get(i).getDisplayName());
                    int lastIndex = startIndex + user.get(i).getDisplayName().length();
                    final int finalI = i;
                    ClickableSpan clickableSpan = new ClickableSpan() {
                        @Override
                        public void onClick(View textView) {
                            //Toast.makeText(mcontext, user.get(finalI).getDisplayName(), Toast.LENGTH_SHORT).show();
                            if(feedsFragment!=null) {
                                ((FeedsFragment)feedsFragment).callUserDetails(user.get(finalI));
                            }
                        }

                        @Override
                        public void updateDrawState(TextPaint ds) {
                            super.updateDrawState(ds);
                            ds.setUnderlineText(false);
                            ds.setColor(Color.BLACK);
                            ds.setFakeBoldText(true);
                        }
                    };
                    //int cityIndex = text.indexOf(city) - 1;
                    spannable.setSpan(clickableSpan, startIndex, lastIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


                }
            }
        }

        mItemTitle.setText(spannable);
        mItemTitle.setMovementMethod(LinkMovementMethod.getInstance());
    }

Conclusion

If you want to implement Hashtag Mentions in android then you will find these steps easier. Implementation of  Hashtag Mentions has very easy steps as described above. You can edit the XML and activity files in your own way to make it more attractive as per your requirements. We have implemented the Hashtag Mentions in the below-listed apps. You can check these apps from the play store.

MeggaMigo
When you use meggamigo, there’s just so much to do! This social networking app can do everything you need to stay connected such as:

  • Get updated through your news feed and see what your friends and family are up to
  • Like, share, react, and comment on your friends’ and families’ posts
  • Post a picture and video, Share the latest news, Share your life

MeggaBuzz
This a short and quick messaging social network that has a limit of 180 characters. With meggabuzz, you can:

  • Share the latest buzz
  • Catch the news
  • See what your friends

References

Further reading

Leave a Comment

Scroll to Top