解决安卓代码动态布局时,相对布局下无法居中显示文字

今天,我在编写一个界面布局的时候遇到了这样一个问题,就是明明我使用了相对布局后无法实现居中显示textview中的文字。我相信有许多小伙伴和我遇到了相同的问题,在这里我把我编写的形式以及解决的方式在这里说下。
首先我的xml文件如下:

<?xml version="1.0" encoding="utf-8"?>

<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);却不能居中,不断调试却无效果。最后终于可以了。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_41620230

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值