2014-09-04 55 views
1

我有一個editTextbox,如下所示,需要在它的中間設置光標。如何在已經填充提示的中心設置EditText光標位置?

<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"/> 

我想:

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

長度返回0,因爲沒有真正的文本在EDITTEXT箱存在。 誰能告訴我如何設置初始光標位於「Hello My World」的中間位置?

感謝提前!

+0

記錄長度,看看它是否爲零,如果不是,那麼它應該工作 – Elltz 2014-09-04 03:45:12

+0

光標已經在中間 – 2014-09-04 03:51:07

+0

你的提示會不斷變化或者它是固定的? – Aniruddha 2014-09-04 04:47:57

回答

0

試試這個:

<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"/> 

參考:

Android: Edittext with gravity center not working on device

+0

我在嘗試之前閱讀這篇文章,但沒有奏效。光標停留在文本提示的前面。 – beachboy 2014-09-04 14:05:38

0

您可以使用下面的,如果你的hint不是動態的。

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

給一些int值給left,光標會移動。

或者您可以在xml文件中將android:paddingLeft="30dp"添加到您的EditText中。

+0

它不僅將整個提示文本向右移動30dp,而且不能使用左側的第一個30dp。我需要的是將光標始終保持在中間位置,並且只要用戶開始輸入,它就從左邊的0dp區域開始。 – beachboy 2014-09-04 14:09:03

0

試試這個,只是直接在你的XML文件中添加請求焦點。您不必在活動中以編程方式設置光標。

<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> 

如果你沒有在你的EditText添加請求焦點光標將不會顯示,除非你在它挖掘出來。 希望得到這個幫助。

+0

我發現沒有任何效果嘗試此操作 – beachboy 2014-09-04 14:10:15

+0

@beachboy您的edittext可以提供什麼樣的屏幕截圖? – yhel 2014-09-05 00:12:58