Java Question How to get EditText cursor position x,y?

BobsYourUncle

Member
Licensed User
Longtime User
Hi,
I have found some Java code that will give the x,y coordinates of the cursor in an EditText view.

B4X:
int pos = editText.getSelectionStart();
Layout layout = editText.getLayout();
int line = layout.getLineForOffset(pos);
int baseline = layout.getLineBaseline(line);
int ascent = layout.getLineAscent(line);
float x = layout.getPrimaryHorizontal(pos);
float y = baseline + ascent;

Please can someone give me a few pointers as to how I declare editText in my library, so it points at my EditText1 view on my actual B4A activity.

(Or is this more easily done with Reflection, from with B4A)?

Any help would be greatly appreciated!
 

COBRASoft

Active Member
Licensed User
Longtime User
Erel, this is a nice example of something that should be added in the core of B4A (or perhaps in an advanced GUI lib). I'm sure more people need this and not everybody is able to create their own libs (due to lack of Java knowledge).
 

BobsYourUncle

Member
Licensed User
Longtime User
Success! Very easy in the end. Here's the code, in case it's useful to anyone else.

B4X:
public float getCursorX(EditText editText){
   float ret = -1;
   try{
      int pos = editText.getSelectionStart();
      Layout layout = editText.getLayout();
      float x = layout.getPrimaryHorizontal(pos);
      
          ret = x;
      
   }
   catch(Exception exception){
      Log.d("getCursorX", exception.toString());
   }
   return ret;
}
 
Top