android xmlns:tools用法
Android開發中在布局檔案裡面都會有如下面的內容:
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
/>
其中tools起什麼作用呢?可以參考文檔http://tools.android.com/tech-docs/tools-attributes
在該文檔中列舉了很多tools的方法,比如tools:ignore/tools:targetApi/tools:locale等方法,但是我們今天要討論的則是該文檔中最後面提到的內容Designtime Attributes,文檔地址為http://tools.android.com/tips/layout-designtime-attributes
在官方文檔中有說這麼一句: These are attributes which are used when the layout is rendered inthe tool, but have no impact on the runtime. This is useful if you for examplewant to put sample data in your textfields for when you are editing the layout,but you don't want those attributes to affect your running app.
這些屬性用於渲染布局,而不會影響到程式運行。也就是說只在預覽布局時出現,在程式運行時相當於該屬性不存在。
這個說明非常有意思,比如我們在布局檔案中想要顯示一段文字時,而該文字內容在程式中可能動態變化,特別是有參數的字串內容%1$s之類的內容,以前必須使用android:text顯示,然後調整這段文字的大小顏色參數,然後完成後刪除android:text屬性。有了tools參數後,可以直接使用tools:text在預覽時顯示文字即可,省卻了上面刪除的麻煩。
目前常用的有tools:text, tools:visibility, tools.src, tools.background
官方文檔中也列出了一些限制,如下:
- Currently only overriding existing attributes is supported. We may want to define some additional convenience attributes to make it simple to for example choose which child in a ViewFlipper to show etc. 當前只支援overriding已有的屬性
- You have to manually edit in your designtime attributes at this time