Android中光标如何置于中心位置

5

我正在开发一个包含登录界面的Android应用程序。在我的登录界面中,我有用户名和密码EditText字段。在EditText中,我需要将提示设置为“输入您的用户名”,并居中对齐,因此我将重力设置为“center”,但现在问题是光标也在中心位置可见,我需要将光标定位到左侧。我还尝试了下面的代码。

edtUserName.setSelection(1);

这是我的xml代码:
 <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>

请帮我解决这个问题。提前致谢。


嗨,现在我已经添加了XML代码,请刷新并查找代码。 - Dhamodharan
你解决了吗? - Salmaan
4个回答

6
你可以尝试这个。
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:textAlignment="center"
android:ellipsize="end"
android:gravity="center"/>

3
你可以通过编程实现这个目标!
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); 
        }
    }
}

0

改变重力:

 android:gravity="center_vertical"

android:gravity="center_horizontal" 也可以起作用。 - oguzhan

0

我认为这会对你有所帮助。

android:gravity设置了它所用的View内容的重力。 android:layout_gravity设置了其父级中View或Layout的重力。 以下是一个示例:Example


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接