在編寫xml文件時,為了預覽效果,經常會使用預設填上一些內容,比如TextView時,隨便寫上一個text 但是如果這個在實際發佈的時候忘記了刪除這個text,就有可能出現問題了 其實在Android Studio上,可以使用一個更加優雅和高效的方式,那就是使用tools屬性 首先添加tools的n ...
在編寫xml文件時,為了預覽效果,經常會使用預設填上一些內容,比如TextView時,隨便寫上一個text
<TextView
...
android:text="Name:" />
但是如果這個在實際發佈的時候忘記了刪除這個text,就有可能出現問題了
其實在Android Studio上,可以使用一個更加優雅和高效的方式,那就是使用tools屬性
首先添加tools的namespace
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
...
然後就可以放心的使用了
<TextView
tools:text="Name:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
tools屬性是designtime attribute,也就只有在Android Studio中進行layout預覽的時候有效,運行的時候這些屬性會被刪除
一般android:命名空間有的屬性,使用tools都會有效
tools屬性除了進行屬性值的預覽外,還可以對一些屬性進行unset,因為在預覽的時候,tools:屬性會覆蓋android:屬性
舉個例子,有個按鈕預設是隱藏的,但是你想在編輯layout的時候還能看到他,但是有不想反覆的修改屬性,可以這樣做
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First"
android:visibility="invisible"
tools:visibility="visible" />
在編輯layout的時候,這Button是可見的,但是正真打包的時候,這個Button是不可見的
除了基本屬性,還有一些神奇的屬性可以使用:
tools:listitem tools:listheader tools:listfooter
在ListView, RecyclerView中預覽item
tools:layout
Fragment標簽使用,告訴Fragment使用哪個佈局
tools:showIn
如果layout被include,使用tools:showIn指定父layout,就可以預覽include後的效果了,如果使用merge標簽作為根佈局,看上去就不會一團糟了
tools:parent
使用自定義view,如果layout的根節點為merge,指定自定義view,例如
tools:parent="com.example.CustomView"
merge內的控制項就會根據CustomView進行佈局
tools:context
這個比較常見,新建一個Activity的時候都有,可以通過知道的context讀取Activity的主題,標題,甚至menu,然後顯示預覽
tools:ignore
忽略lint的檢查
tools:targetApi
tools:locale
制定預設資源文件夾的地區,制定為中國,系統就不會警告沒有添加中文的翻譯了