How to Set Cursor Position in Edittext

How to set cursor position in EditText?

Where position is an int:

editText1.setSelection(position)

Set cursor position in android Edit text

You can achieve this by using :

Edittext.setSelection(Edittext.length());

this will put the cursor position in the end. otherwise you can get the text in a string and check the text position where you want to put the cursor and do it like this

String text = edittext.getText().toString();

for(int i = 0; i <text.length();i++)
{
//your logic here to check the position of text
}

and then

Edittext.setSelection(position);

set cursor position of edittext in center...!

I found now what is main problem...
Problem is in the API level..

I change API level of my program.

Below API 15, cursor is set in the center in my application..

From API 16, cursor position set to start of the Hint text...!!!

Set cursor position in edittext android

I'm sure you have resolved the problem after 3 months but I want to answer for someone who faces the same problem.
The problem is with this attribute: android:gravity="top"
When you use it, it doesn't let the cursor to move. I don't know why but after I deleted this line, it worked.

Set cursor position in Edit Text android

You have to use setSelection(int position) method of edittext.
Like edt.setSelection(0)

How to have fixed cursor position for EditText?

You can apply this trick, This worked for me.
Just disable the cursor from edittext and on its click listener add your code that will keep the cursor on right most.

Here is code that i tried.

<EditText
android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="12"
android:background="@color/white"
android:padding="@dimen/activity_margin_10"
/>

Java Code

EditText mEditText;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);

mEditText = (EditText)findViewById(R.id.edit); // Initialzation of Edittext
mEditText.setSelection(mEditText.getText().length()); // After initialization keep cursor on right side
mEditText.setCursorVisible(false); // Disable the cursor.

/*
Add Click listener and on put your code that will keep cursor on right side
*/
mEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mEditText.setSelection(mEditText.getText().length());
}
});
}

Hope it will help you.

MVVM Set Cursor in end of text in EditText when using afterTextChanged fuction

you could a BindingAdapter for it

@BindingAdapter("cursorPosition")
@JvmStatic
fun setCursorPosition(editText: EditText, value: String?) {
value ?: return
editText.setSelection(value.length)
}

and in your layout use is as

cursorPosition="@{viewmodel.amount}"


Related Topics



Leave a reply



Submit