一、为何要使用tools
安卓开发中,在写布局代码的时候,AS可以看到布局的预览效果。以TextView为例
<TextView
android:id="@+id/tv_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="张三"/>
我们开发界面的时候,为了方便预览效果,经常都会给TextView设置一个android:text,以便预览效果,然后等开发调试完毕后再删除该text,然而实际情况是,
我们开发完毕后往往忘了删除,导致程序可能因为没有设置text而显示默认的text,从而导致显示错误。比如
TextView tv_username = (TextView) findViewById(R.id.tv_username);
if(null!=user){
tv_username.setText(user.getUserName());
}
上面判断当user不等于null时,才给TextView设置,如果user=null的话,则会显示默认布局中的”张三“,这样就导致了显示错误。
因此为了避免上述问题,我们可以使用tools命名空间以及其属性来解决
xmlns:tools="http://schemas.android.com/tools"
tools可以告诉Android Studio,哪些属性在运行的时候是被忽略的,只在设计布局的时候有效。比如我们要让android:text属性只在布局预览中有效可以这样
<TextView
android:id="@+id/tv_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
tools:text="张三" />
tools可以覆盖android的所有标准属性,将android:换成tools:即可。
在运行的时候tools:本身是被忽略的,不会被带进apk中,不用我们手动删除。
二、tools支持的属性
1、支持所有的android属性,只需要将android:换成tools:即可2、压制lint警告
- tools:ignore
表示忽略这个警告
比如忽略ImageView的contentDescription属性,则添加tools:ignore="contentDescription",如果不知道具体属性,可使用tools:ignore="all"压制所有警告。
- tools:targetApi
指定该View显示的目标api
假设你的应用支持minSdkLevel=15,而你使用了api21中的控件比如RippleDrawable,就可以使用tools:targetApi不显示这个警告
3、其他非android标准属性- tools:context
比如tools:context="com.support.tools.MainActivity"
- tools:menu
比如tools:menu="main,main2"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:menu="main,main2"
">
</LinearLayout>
需要注意,当主题为Theme.AppCompat时,这个属性不起作用
- tools:actionBarNavMode
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:actionBarNavMode="tabs"
">
</LinearLayout>
注意:该属性只有holo主题才有效。
- tools:listitem/listheader/listfooter
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:listheader="@layout/list_header"
tools:listitem="@layout/list_item"
tools:listfooter="@layout/list_footer"
/>
- tools:layout
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.support.tools.MyFragment"
tools:layout="@layout/fragment"
/>
参考:
Tools of the trade——Part 1
Tools of the trade——Part 2