天天看點

tools:context用法

tools可以告訴Android Studio,哪些屬性在運作的時候是被忽略的,隻在設計布局的時候有效。比如我們要讓android:text屬性隻在布局預覽中有效可以這樣

<TextView

 android:id="@+id/text_main"

 android:layout_width="match_parent"

 android:layout_height="wrap_content"

 android:textAppearance="@style/TextAppearance.Title"

 android:layout_margin="@dimen/main_margin"

 tools:text="I am a title" />      

tools可以覆寫android的所有标準屬性,将android:換成tools:即可。同時在運作的時候就連tools:本身都是被忽略的,不會被帶進apk中。

其中的tools:context

context屬性其實正是的稱呼是activity屬性,有了這個屬性,ide就知道在預覽布局的時候該采用什麼樣的主題。同時他還可以在android studio的java代碼中幫助找到相關的檔案(Go to Related files)

該屬性的值是activity的完整包名

<LinearLayout

  xmlns:android="http://schemas.android.com/apk/res/android"

  xmlns:tools="http://schemas.android.com/tools"

  android:id="@+id/container"

  android:layout_width="match_parent"

  android:layout_height="match_parent"

  android:orientation="vertical"

  tools:context="com.android.example.MainActivity">  <!-- ... -->

</LinearLayout>      

tools 相關的屬性是提示給編輯器的,也就是用來輔助編輯器展示效果,在真機上這些屬性是沒有作用的。例如這裡的tools:context 就是将這個 layout 檔案和後面的 Activity 進行關聯,這樣編輯器在展示布局效果的時候,就能針對Activity 的一些屬性進行有針對性的處理。

繼續閱讀