1

I have a editTextbox as below and need to set cursor in the middle of it.

<EditText
    android:id="@+id/editText"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:layout_centerHorizontal="true"
    android:gravity="center_horizontal"
    android:textCursorDrawable="@drawable/my_custom_cursor"
    android:hint="Hello My World"/>

I tried:

editText = (EditText) findViewById(R.id.editText);
    int length = editText.getHint().length();
    editText.setSelection(length/2);  <-- problem

The length returns 0 since there is no real text exist in the editText box. Could anyone tell me how I can set initial cursor locate at the middle of "Hello My World" ?

Thanks advance!

beachboy
  • 43
  • 1
  • 6

3 Answers3

0

Try this:

<EditText
    android:id="@+id/editText"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:hint="Hello My World"/>

Reference:

Android: Edittext with gravity center not working on device

Community
  • 1
  • 1
PLP
  • 714
  • 3
  • 13
0

You can use the below if your hint is not dynamic.

 editText.setPadding (int left, int top, int right, int bottom);

Just give some int value to left, and the cursor will move.

Or you can add android:paddingLeft="30dp" to your EditText in xml file.

Aniruddha
  • 4,477
  • 2
  • 21
  • 39
  • It not only moves entire hint text to the right by 30dp but also can't use the first 30dp on the left side. What I need is just keep the cursor centered in the middle initially and as soon as user start typing, it starts from left 0dp area. – beachboy Sep 04 '14 at 14:09
0

Try this, just add request focus directly on your XML file. You don't have to do setting your cursor programmatically on your Activity.

<EditText
    android:id="@+id/editText"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:layout_centerHorizontal="true"
    android:gravity="center"
    android:hint="Hello My World">

 <requestFocus />

</EditText>

If you don't add request focus on your EditText the cursor will not show unless you tapped on it. Hope this help.

yhel
  • 92
  • 1
  • 6