我似乎無法在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居中。
嘗試在佈局,而不是...使用{android:layout_centerHorizontal}。 – Wizard
我必須以編程方式進行。 – rpurohit
嘗試'editTextParams.addRule(RelativeLayout.CENTER_IN_PARENT,RelativeLayout.TRUE);' – Wizard