Dhamodharan
Dhamodharan

Reputation: 305

Cursor in center position in android

I am working with Android app which contains login screen. In my login screen, I have Username and Password EditTtext fields. In EditText, I need the hint as "Enter your Username" in center aligned, so I set the gravity as "center" but now, the problem is that the cursor is also visible in center position, I need cursor in left positioned. And I also tried the below coding.

edtUserName.setSelection(1);

This is my xml code:

 <EditText
      android:id="@+id/edt_login_username"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:background="@drawable/bg_txt_field"
      android:ellipsize="start"
      android:focusableInTouchMode="true"
      android:hint="Enter Username"
      android:maxLines="1"
      android:singleLine="true"
      android:textStyle="italic"
      android:typeface="serif"
      android:gravity="center">
</EditText>

Please help me to solve this problem. Thanks in advance.

Upvotes: 5

Views: 9437

Answers (4)

Salman khan
Salman khan

Reputation: 1255

You can achieve it programatically!!!

yourEditText.addTextChangedListener(new TextWatcher() {

    public void afterTextChanged(Editable s) {}
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if (s.length() > 0) {
             // puts the caret after the text when unempty
             yourEditText.setGravity(Gravity.CENTER);
        } else {
             // puts the caret at the beginning of the `EditText` when empty
             yourEditText.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); 
        }
    }
}

Upvotes: 3

Carlochess
Carlochess

Reputation: 686

You can try this

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:textAlignment="center"
android:ellipsize="end"
android:gravity="center"/>

Upvotes: 6

Deepanker Chaudhary
Deepanker Chaudhary

Reputation: 1704

Change gravity:

 android:gravity="center_vertical"

Upvotes: 0

Nirav Ranpara
Nirav Ranpara

Reputation: 13785

I think this will help you .

android:gravity sets the gravity of the content of the View its used on. android:layout_gravity sets the gravity of the View or Layout in its parent. And an example : Example

Upvotes: 0

Related Questions