Home > OS >  Xamarin Forms get cursor position in editor control
Xamarin Forms get cursor position in editor control

Time:09-29

How can I get the cursor position inside Editor control?

Ive been looking for an answer but the best I could find was the Cursor class, but that doesnt seem to exist in xamarin.

CodePudding user response:

You could custom a Editor,and use custom renderer to get the SelectionPosition of the EditText.

custom a FormEditor in your fomrs project:

public class FormEditor:Editor
{
    public int SelectionPosition;

    public EventHandler SelectChanageEvent { get; set; }
}

create AndroidEditor in your Android project:

class AndroidEditor : EditorRenderer, EditTextSelectChange
{
    private Context mContext;

    public AndroidEditor(Context context) : base(context)
    {
        mContext = context;
    }

    public void Change(int lastPos, int curPos)
    {

        ((FormEditor)Element).SelectionPosition = curPos;
        ((FormEditor)Element).SelectChanageEvent.Invoke(this, null);
    }

    protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
    {
        base.OnElementChanged(e);
        MyEditText myEditText = new MyEditText(mContext);
        myEditText.SetEditTextSelectChange(this);
        SetNativeControl(myEditText);

    }
}

custom MyEditText in your Android project:

public class MyEditText : FormsEditText
{

    private int mLastPos = 0;
    private int mCurPos = 0;
    private EditTextSelectChange editTextSelectChange;

    public void SetEditTextSelectChange(EditTextSelectChange editTextSelectChange)
    {
        this.editTextSelectChange = editTextSelectChange;
    }
    public MyEditText(Context context) : base(context)
    {
    }


    protected override void OnSelectionChanged(int selStart, int selEnd)
    {
        base.OnSelectionChanged(selStart, selEnd);
        if (editTextSelectChange != null)
        {
            mCurPos = selEnd;
            editTextSelectChange.Change(mLastPos, mCurPos);
            mLastPos = mCurPos;
        }
    }
    public interface EditTextSelectChange
    {
        void Change(int lastPos, int curPos);
    }
}

then use in your page.xaml:

 <local:FormEditor x:Name="editor" Placeholder="Hello"></local:FormEditor>

in your page.xaml.cs:

public YourPage()
  {
        InitializeComponent();
        editor.SelectChanageEvent  = SelectEvent;
  }

  
  private void SelectEvent(object sender, EventArgs e)
  {
     // you could get the Curson Position by editor.SelectionPosition
     Console.WriteLine("curPos = {0}", editor.SelectionPosition);
  }
  • Related