Android:以编程方式在 EditText 中居中文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12043809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:34:14  来源:igfitidea点击:

Android: Center text inside EditText programmatically

androidandroid-edittext

提问by capcom

Is there any way to center the inputted text in an EditTextfield? More specifically, instead of the cursor starting at the left of the box, it should start in the center and move outward towards the left as it is populated with inputs.

有没有办法将输入的文本集中在一个EditText字段中?更具体地说,光标不应从框的左侧开始,而应从中心开始,并在填充输入时向外向左移动。

回答by ColdFire

you should use

你应该使用

 textView.setGravity(Gravity.CENTER_HORIZONTAL);

回答by CommonsWare

Try android:gravity="center_horizontal"in the widget definition in your layout file. This will not strictly "move outward towards the left" -- it should move outward in both directions evenly. If you truly mean you want the text to only be on the left side of the EditText, I doubt that will be possible.

android:gravity="center_horizontal"在布局文件中尝试小部件定义。这不会严格地“向左向外移动”——它应该在两个方向上均匀地向外移动。如果您真的希望文本仅位于 的左侧EditText,我怀疑这是否可行。

回答by Ajay B

Simpler Solution to align text in EditText is to add android:gravity="center" in layout xml. There is no need to add Java code.

在 EditText 中对齐文本的更简单解决方案是在布局 xml 中添加 android:gravity="center"。无需添加 Java 代码。

Tested Sample Code-

测试示例代码-

<EditText
                android:id="@+id/FieldName"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/back"
                android:inputType="numberDecimal"
                android:gravity="center" />