2015-11-18 27 views
1

我似乎無法在RelativeLayout中水平居中EditText。我曾經嘗試這樣做:在RelativeLayout中水平居中編輯文本

RelativeLayout.LayoutParams editTextParams = ((RelativeLayout.LayoutParams) editText.getLayoutParams()); 
     editTextParams.width = 400; 
     editTextParams.addRule(RelativeLayout.CENTER_HORIZONTAL); 
     editText.setLayoutParams(editTextParams); 

這裏是我的佈局XML文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context="com.example.app" 
android:gravity="center_horizontal"> 
<EditText 
    android:layout_width="match_parent" 
    android:layout_height="35dp" 
    android:inputType="textNoSuggestions" 
    android:ems="10" 
    android:id="@+id/usernameField" 
    android:paddingLeft="10dp" 
    android:paddingStart="10dp" 
    android:paddingRight="0dp" 
    android:paddingEnd="0dp" 
    android:hint="Enter username" 
    android:layout_marginRight="16dp" 
    android:layout_marginEnd="16dp" 
    android:layout_marginTop="16dp" /> 
</RelativeLayout> 

我也用瑣碎提出的建議嘗試。

上述事情只是使EditText保持左對齊。我想要EditText居中。

+0

嘗試在佈局,而不是...使用{android:layout_centerHorizo​​ntal}。 – Wizard

+0

我必須以編程方式進行。 – rpurohit

+0

嘗試'editTextParams.addRule(RelativeLayout.CENTER_IN_PARENT,RelativeLayout.TRUE);' – Wizard

回答

0
android:layout_centerInParent="true" 

一下添加到XML的EditText

+0

我必須以編程方式進行。 – rpurohit

0

我懷疑

android:paddingStart="10dp"android:paddingEnd="0dp"在某處干擾。

請嘗試移除它並告訴我們結果?