標籤:android ui 布局
Android開發中在布局檔案裡面都會有如下面的內容:
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/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
- They do not appear as an option in for example the layout editor property sheet.
- Editor code completion does not help you enter these attributes; the easiest way to use them is to first enter them in the Android namespace, and when done replacing the prefix. 目前還只能手動輸入該部分,代碼自動填滿還無法完成
- Note that designtime attributes are supported only for layout files themselves. You cannot use them anywhere else -- in menu XML files, in string resource definitions, etc.只支援layout布局,menu/resource/string暫時不支援,這個說法和http://tools.android.com/tech-docs/tools-attributes中內容有衝突,tools-attributes中提供了<string name="show_all_apps" tools:ignore="MissingTranslation">All</string>以及<resources xmlns:tools="http://schemas.android.com/tools" tools:locale="es">內容
- Designtime attributes can only be used for framework resources, not custom attributes at this point.只能適用於系統提供的屬性,自訂屬性不再這個範圍
- See https://code.google.com/p/android/issues/detail?id=46186 for background or additional requests or comments.
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
android xmlns:tools用法