让预览 RecyclerView 效果更方便的一个小技巧

简评:使用 "@tools:sample/*" 资源来让 RecyclerView(或 ListView)的效果预览更方便。

相信在大多数的 Android 开发中都会和 RecyclerView(或者 ListView)打交道。常有的一个问题就是在编码时,怎么方便的看到和调整每一个 item 的显示效果。html

固然啦,有经验一的开发者确定都知道用 tools:namespace 来帮忙,今天要介绍的固然不仅是这么简单。android

首先,假设咱们要实现的效果相似下面这样(每一个 item 左边还有个头像):json

clipboard.png

这里就是经过 tools:text 来在 Android Studio 的 Preview 视图中直接显示一些简单内容(ImageView 也可使用 tools:src)。dom

<TextView
    android:id="@+id/name"
    ...
    tools:text="Mark Allison"/>

如今,在 Android Studio 3.0 或以上版本中咱们有了更好的方法来在开发时直接显示一些示例数据 - 那就是使用 "tools:sample/" 中提供的数据。*布局

<?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>

效果:编码

clipboard.png

固然,这些自带的数据极可能没办法知足你的需求(好比只有英文),咱们还能够本身建立 Sample 数据:spa

clipboard.png

点击以后,文件实际所在的位置:code

clipboard.png

添加头像图片(这里用的是 Android 矢量图,也能够是其余格式的图片):xml

clipboard.png

<ImageView
    android:id="@+id/avatar"
    ...
    tools:src="@sample/avatars" />

更棒的地方在于,咱们还能够经过 JSON 文件的方式来组织咱们的数据。好比,建立一个名为 users.json 的文件:htm

{
  "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 不会被打包到 APK 中,所以没必要担忧会增长应用的体积。

官方文档:https://developer.android.com...
英文原文:Tool Time – Part 1 & Tool Time – Part 2

相关文章
相关标签/搜索