简体   繁体   English

Android如何动态居中编辑文本

[英]Android how to center an EditText dynamically

Goal 目标

I have a RelativeLayout with some TextView's sets in xml and I want to add dynamically some EditText's, one below another. 我有一个RelativeLayout,其中的xml中有一些TextView的集合,我想动态添加一些EditText的集合,一个在另一个之下。

Problem 问题

How can I center horizontally those EditText's? 如何将那些EditText的水平居中放置?

Code

Here is my code up to date: 这是我最新的代码:

/* Layout with EditText's */
RelativeLayout parentLayout = (RelativeLayout)
findViewById(R.id.relativeLayoutLectura);
EditText editText = new EditText(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// If it's first EditText to insert, goes below another linearLayout set before
if(id == -1) {
    editText.setId(1);
    params.addRule(RelativeLayout.BELOW, R.id.linearLayoutMensajeLectura);
} else {
    editText.setId(id);
    params.addRule(RelativeLayout.BELOW, id-1);
}
editText.setLayoutParams(params);
editText.setGravity(Gravity.CENTER_HORIZONTAL); //It does nothing
parentLayout.addView(editText);

Thanks in advance. 提前致谢。

Setting the gravity of the edit text will effect where the text is displayed inside it. 设置编辑文本的重力将影响文本在其中显示的位置。

As you're putting it into a RelativeLayout, you need to params.addRule(RelativeLayout.CENTER_IN_PARENT) or params.addRule(RelativeLayout.CENTER_HORIZONTAL) 将其放入RelativeLayout时,需要params.addRule(RelativeLayout.CENTER_IN_PARENT)params.addRule(RelativeLayout.CENTER_HORIZONTAL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM