今天,我在编写一个界面布局的时候遇到了这样一个问题,就是明明我使用了相对布局后无法实现居中显示textview中的文字。我相信有许多小伙伴和我遇到了相同的问题,在这里我把我编写的形式以及解决的方式在这里说下。
首先我的xml文件如下:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="@color/gray"
>
<TextView
android:id="@+id/user_info_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="个人信息" />
</RelativeLayout>
<LinearLayout
android:id="@+id/layout_user_personinfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/user_info_personname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:text="姓名" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:background="#40E0D0"
>
<TextView
android:id="@+id/user_personnames"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
android:text="张三"
android:textColor="@color/login_gray" />
<TextView
android:id="@+id/user_personnames_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=">"
android:layout_centerVertical="true"
android:textColor="@color/login_gray"
/>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="2px"
android:textColor="#000"
/>
</LinearLayout>
由于我自己使用代码布局实现居中显示的,但是效果却是这样的。代码布局所用代码如下图:
明明代码中已经调用了
RelativeLayout.LayoutParams editnameparam = new RelativeLayout.LayoutParams((int)(screenWidth0.5), (int)(screenHeight0.2));
editnameparam.addRule(RelativeLayout.CENTER_VERTICAL);
但是文字还不是自己想要的位置,我特地将背景色设置了下,不是居中的。
我自己尝试了许多方式,最后我决定对textView的高度进行操作,将其设置成自适应的模式,即:RelativeLayout.LayoutParams.WRAP_CONTENT
后发现
打到我预期的效果,真心不错。
刚开始我一直纠结为什么已经使用了 editnameparam.addRule(RelativeLayout.CENTER_VERTICAL);却不能居中,不断调试却无效果。最后终于可以了。