Android Question Help with Java function GetSpans

B G

Member
Licensed User
Longtime User
Erel (or anyone else who can help),

I have recently written and posted to the forum a class which enables users to type and edit text using various colors and styles.

It uses a lot of Android APIs which I have been able to call using B4A code. However there is one function that I haven't been able to convert to B4A properly. At the moment I use Java code for that function and it works quite well, there is no problem with it. However, I would like to be able to convert that Java function to B4A code if I could.

The function is used to get the Spans from a SpannableStringBuilder object. The native Android function is "getSpans" and I use it like this;

1) Get the SpannableStringBuilder object from my EditText view.

B4X:
Dim RefET as reflector
refET.Target = EditText
Dim SpannableString As JavaObject
SpannableString = refET.RunMethod("getText") ' includes the text with all spans

2) I then call the Java code

B4X:
Dim joGetAllSpans As JavaObject
joGetAllSpans.InitializeContext
Dim joSpans As JavaObject = joGetAllSpans.RunMethod("getAllSpans",Array(SpannableString))

3) The Java code

B4X:
import android.text.SpannableStringBuilder;
import java.util.ArrayList;

 public static ArrayList getAllSpans(SpannableStringBuilder sourcetext) {
    
    Object[] spans = sourcetext.getSpans(0, sourcetext.length(), Object.class);
    ArrayList<Object> mylist = new ArrayList<Object>();
    for (Object span : spans) {
         mylist.add(span);
        }
        return mylist;
        }

4) Go thru each span and save the details.

B4X:
Dim Size As Int = joSpans.RunMethod("size",Null)
Dim SpanStart, SpanEnd As Int, Parameter As Object
For Idx = 0 To Size - 1
    Dim joSpan As JavaObject = joSpans.RunMethod("get",Array As Object(Idx))
    Dim r As Reflector
    r.Target = joSpan
    r.Target = r.RunMethod("getClass")
    Dim ClassName As String = r.RunMethod("getName")
    SpanStart = 0 : SpanEnd = 0 : Parameter = null
    Select Case ClassName
        Case "android.text.style.ForegroundColorSpan"
            SpanStart = SpannableString.RunMethod("getSpanStart", Array As Object(joSpan))
            SpanEnd = SpannableString.RunMethod("getSpanEnd", Array As Object(joSpan))
            Parameter = joSpan.RunMethod("getForegroundColor",Null)
        ...
        ...
        Case Else
                Continue
        End Select

If anyone can help code that Java function in B4A, I would be most appreciative.
 
Top