2013-07-08 12 views
0

目標的Android如何中心一個EditText動態

我有一些的TextView的套在XML中的RelativeLayout,我要動態地添加一些EditText上的,一個下面的另一個。

問題

我怎麼能水平居中的EditText上的?

代碼

下面是我的代碼最新:

/* 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); 

在此先感謝。

+0

添加您的EditText的集裝箱(如LinearLayout中),那麼這個容器添加到您的父RelativeLayout的。 –

回答

0

設置編輯文本的重力會影響文本顯示在其中的位置。

當你把它變成一個RelativeLayout的,您需要params.addRule(RelativeLayout.CENTER_IN_PARENT)params.addRule(RelativeLayout.CENTER_HORIZONTAL)

相關問題