安卓开发小技巧:让预览的时候可以看到文字,运行之后不显示文字

前言

在实际开发过程中,我们可能会遇到这么一个问题:我们为了可以实时地看到显示效果,会在xml上加一些文字,如下图:
在这里插入图片描述

对应的xml代码如下:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:layout_weight="1"
            android:textColor="#333"
            android:text="姓名"/>
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:textColor="#666"
            android:text="王大便"/>
    </LinearLayout>

当程序真正运行起来的时候,上图中的姓名会从网络中获取下来,然后把“王大便”给替换掉。如果网速很快,“王大便”一下子就被替换掉了,这倒没什么问题,但是网络是有可能出问题的,导致加载用户姓名失败,此时“王大便”就会显示在界面上。一般人采取的做法是:直接在xml布局里面删除android:text=“王大便”,但是删除了我们就看不到预览效果了。既要想看到预览效果,又想要程序在运行时,不显示“王大便”,该怎么做呢?

方法

第一种:直接用“- - -”代替上图中的“王大便”

这种方法虽然在网络不好的情况下,没有给客户造成太大的影响,但实际上也没有起到真正的预览效果,只是用来占位而已。此法欠佳。

第二种:使用tools命名空间

xml代码如下:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:layout_weight="1"
            android:textColor="#333"
            android:text="姓名"/>
        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:textColor="#666"
            tools:text="王大便"/>
    </LinearLayout>

我们把android:text="王大便"改成了tools:text=“王大便”,当程序运行起来的时候,你就看不到王大便啦,如下图:
在这里插入图片描述
关于tools命名空间,其实默认生成布局的根布局,就已经添加有了,即下面这行代码:

xmlns:tools="http://schemas.android.com/tools"

只有添加了这个命名空间,你才能使用tools:text,这跟C++中的命名空间有点类似。

总结

使用上述方法二可以起到两个作用:
①可以实时看到预览效果
②不会干扰运行时的界面,网络加载失败时,界面上不会看到在xml布局中写死的文字。
但是方法二的一个缺点就是AS没有提示,需要你手动打出tools替换掉android。也不能说是缺点吧,毕竟手输一个单词也花不了你多长时间,不能完全依赖AS的智能提示。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值