Reputation: 351
I am developing a simple app using Maui .net but facing some challenge perhaps you can give some advice.
I have a multiline text field of type "Editor" and I have one button. The onclicked event of the button should insert the button label text into the Editor mentioned above (very simple task). Now, the issue is when I use the myEditor.Text.Insert(myEditor.Text.Length, myButton.Text)
the inserted text inserts fine, but the blinking text cursor moves to the far left of the Editor field, instead of staying at the far right.
I tried working around this issue but manually moving the text cursor using the myEditor.CursorPosition
but the problem is what if the user decided to manually change text cursor location? then pressing the button would insert at the myEditor.Text.Length
index, thus ignoring the user's intent to insert the text at a specified index.
I wasn't able to find a method that triggers an event when the text cursor moves inside a text Editor in Maui (so that I can handle it in my own way)
Note: When typing using the Android keyboard, there are no issues at all. but only if inserting text programmatically using .Insert(index,string)
Thanks.
Upvotes: 1
Views: 2588
Reputation: 351
Updating Visual Studio to version 17.3.0 Preview 5.0 fixed the issue without further tweaks. This fix came in parallel with the time I was facing this issue and looking for a fix 😅
Upvotes: 0
Reputation: 14244
You can try to use the handler to get the cursor position when you insert the text into the Editor.
Declare the control on the android platform:
#if ANDROID
AppCompatEditText nativeEditText;
#endif
Create the method which can get the control's cursor position for android:
void GetCursorPosition ()
{
Microsoft.Maui.Handlers.EditorHandler.Mapper.AppendToMapping("MyCustomization", (handler, view) =>
{
#if ANDROID
nativeEditText = handler.PlatformView;
});
}
Add code in the button's clicked event:
int cursorPosition = 0;
private void Button_Clicked(object sender, EventArgs e)
{
cursorPosition = nativeEditText.SelectionStart; //get the cursor position if user chooses a position by tapping the editor
string insertText = button.Text;
if (nativeEditText.IsFocused == true)
{
editor.Text = editor.Text.Insert(cursorPosition, insertText);
editor.CursorPosition = cursorPosition + insertText.Length;
//set the position at the end of text inserted
}
else
{
editor.Text = editor.Text.Insert(editor.Text.Length, insertText);
}
}
Upvotes: 0