Search code examples
androidspannablestring

How to make spannable with multiple text?


String sentence="this is @part 1 and #here another and #another one @user  #newone @itsme ";

    textView.setMovementMethod(LinkMovementMethod.getInstance());
    textView.setText(addClickablePart(sentence), BufferType.SPANNABLE);


    private SpannableStringBuilder addClickablePart(String str) {
    SpannableStringBuilder ssb=new SpannableStringBuilder(str);

    int idx1=Math.min(str.indexOf("@"),str.indexOf("#") );

    int idx2=0;
    while (idx1!=-1) {
        idx2=str.indexOf(" ", idx1) + 1;

        final String clickString=str.substring(idx1, idx2);
        ssb.setSpan(new ClickableSpan() {

            @Override
            public void onClick(View widget) {
                Toast.makeText(getApplicationContext(), clickString,
                        Toast.LENGTH_SHORT).show();
            }
        }, idx1, idx2, 0);

        idx1=Math.min(str.indexOf("#", idx2),str.indexOf("@", idx2) );

    }

    return ssb;
}

its working fine for first five words but left last one (@itsme). it lefts only last one (no matter whats the length of string).


Solution

  • put one condition in while statement for checking string size.

    i think idx2 in last loop is 0, because str.indexOf() is -1 then -1 +1 = 0.

    so you check that if idx2 is 0 then make clickable until last of size

    Use following code:

    while (idx1 != -1) {
    
                idx2 = sentence.indexOf(" ", idx1) + 1;
    
                if(idx2 == 0)  
                     idx2 = sentence.length(); // or str.lenght()-1 
    
                idx2 = sentence.indexOf(" ", idx1) + 1;
    
                final String clickString=str.substring(idx1, idx2);
                ssb.setSpan(new ClickableSpan() {
    
                    @Override
                    public void onClick(View widget) {
                         Toast.makeText(getApplicationContext(), clickString,
                              Toast.LENGTH_SHORT).show();
                  }
             }, idx1, idx2, 0);
    
                idx1 = FindMin(idx2+1 , sentence);
            }
    

    FindMin is:

    public int FindMin(int i2 , String mystr)
        {
            int idx1 = mystr.indexOf("@" , i2);
            int idx2 = mystr.indexOf("#" , i2);
    
    
            int minIndex;
            if(idx1 >= 0 && idx2 >= 0 )
             minIndex  =  Math.min(mystr.indexOf("@" , i2) ,mystr.indexOf("#" , i2) );
    
            else if (idx1 >= 0)
              minIndex = idx1;
    
            else
               minIndex = idx2;
    
            return minIndex;
        }