簡(jiǎn)評(píng):使用 "@tools:sample/*" 資源來讓 RecyclerView(或 ListView)的效果預(yù)覽更方便。
相信在大多數(shù)的 Android 開發(fā)中都會(huì)和 RecyclerView(或者 ListView)打交道。常有的一個(gè)問題就是在編碼時(shí),怎么方便的看到和調(diào)整每個(gè) item 的顯示效果。
當(dāng)然啦,有經(jīng)驗(yàn)一的開發(fā)者肯定都知道用 tools:namespace 來幫忙,今天要介紹的當(dāng)然不只是這么簡(jiǎn)單。
首先,假設(shè)我們要實(shí)現(xiàn)的效果類似下面這樣(每個(gè) item 左邊還有個(gè)頭像):

這里就是通過* tools:text* 來在 Android Studio 的 Preview 視圖中直接顯示一些簡(jiǎn)單內(nèi)容(ImageView 也可以使用 tools:src)。
<TextView
android:id="@+id/name"
...
tools:text="Mark Allison"/>
現(xiàn)在,在 Android Studio 3.0 或以上版本中我們有了更好的方法來在開發(fā)時(shí)直接顯示一些示例數(shù)據(jù) - 那就是使用 "tools:sample/" 中提供的數(shù)據(jù)。*
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
...>
<ImageView
android:id="@+id/avatar"
...
tools:src="@tools:sample/avatars" />
<TextView
android:id="@+id/name"
...
tools:text="@tools:sample/full_names" />
<TextView
android:id="@+id/city"
...
tools:text="@tools:sample/cities" />
<TextView
android:id="@+id/date"
...
tools:text="@tools:sample/date/ddmmyy" />
<TextView
android:id="@+id/description"
...
tools:text="@tools:sample/lorem/random" />
</android.support.constraint.ConstraintLayout>
效果:

當(dāng)然,這些自帶的數(shù)據(jù)很可能沒辦法滿足你的需求(比如只有英文),我們還可以自己創(chuàng)建 Sample 數(shù)據(jù):

點(diǎn)擊之后,文件實(shí)際所在的位置:

添加頭像圖片(這里用的是 Android 矢量圖,也可以是其他格式的圖片):

<ImageView
android:id="@+id/avatar"
...
tools:src="@sample/avatars" />
更棒的地方在于,我們還可以通過 JSON 文件的方式來組織我們的數(shù)據(jù)。比如,創(chuàng)建一個(gè)名為 users.json 的文件:
{
"data": [
{
"city": "北京",
"avatar": "@sample/avatars",
},
{
"city": "上海",
"avatar": "@sample/avatars"
},
{
"city": "廣州",
"avatar": "@sample/avatars"
},
{
"city": "深圳",
"avatar": "@sample/avatars"
}
]
}
item 的部分布局代碼:
<ImageView
android:id="@+id/avatar"
...
tools:src="@sample/users.json/data/avatar" />
<TextView
android:id="@+id/city"
...
tools:text="@sample/users.json/data/city" />
...
此外,定義的這些 sample data 不會(huì)被打包到 APK 中,因此不必?fù)?dān)心會(huì)增加應(yīng)用的體積。
官方文檔:https://developer.android.com/studio/write/tool-attributes.html#toolssample_resources
英文原文:Tool Time – Part 1 & Tool Time – Part 2
推薦閱讀:在 Android 中實(shí)現(xiàn) Redux 的一點(diǎn)經(jīng)驗(yàn)