从最近ADT的新版本开始,我注意到布局XML文件上的这个新属性,例如:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity" />

“工具:上下文”的用途是什么?

它怎么知道写在那里的活动的确切路径?它会查看manifest里面的应用程序包吗?

它局限于扩展Context的类还是仅仅局限于活动?它对ListView项目等有用吗?


当前回答

此属性声明默认情况下该布局与哪个活动相关联。这使编辑器或布局预览中需要活动知识的功能成为可能。

其他回答

此属性声明默认情况下该布局与哪个活动相关联。这使编辑器或布局预览中需要活动知识的功能成为可能。

根据Android工具项目网站:

工具:上下文

This attribute is typically set on the root element in a layout XML file, and records which activity the layout is associated with (at designtime, since obviously a layout can be used by more than one layout). This will for example be used by the layout editor to guess a default theme, since themes are defined in the Manifest and are associated with activities, not layouts. You can use the same dot prefix as in manifests to just specify the activity class without the full application package name as a prefix.

<android.support.v7.widget.GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"    
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">  

用于:Studio和Eclipse中的布局编辑器,Lint

工具:上下文= "。MainActivity” 这一行在XML文件中使用,指示使用哪个Java源文件来访问该XML文件。 这意味着为特定的Java文件显示XML预览。

这是最好的解决方案: https://developer.android.com/studio/write/tool-attributes

这是设计属性 我们可以像这样在XML中设置活动上下文

tools:context=".activity.ActivityName"

适配器:

tools:context="com.PackegaName.AdapterName"

单击标记的图标可以导航到java类 工具有更多的功能

tools:text=""
tools:visibility:""
tools:listItems=""//for recycler view 

etx

其他答案所缺少的一个东西是任何类的上下文部分,可以与任何扩展上下文的类一起使用。

context是在Android Studio和Android Gradle插件中引入的属性。它在布局文件中用于指定将在其中使用布局的上下文。

tools命名空间用于指定在运行时不使用的属性,但由Android Studio布局编辑器和其他工具使用,以让您更好地控制如何呈现布局。context属性允许您指定表示布局上下文的Java类的完全限定名称。当布局在编辑器中呈现时,布局编辑器使用它来确定应该将哪些主题和属性应用于布局。

它正在查看清单内的应用程序包。它被用来知道被写在那里的活动的确切路径。

context属性可以与任何扩展context的类一起使用,比如活动、服务或应用程序。然而,它最常用于Activity类,因为它们是大多数应用程序的主要入口点。

context属性不仅仅局限于活动,它可以用于任何扩展context的java类。它可以用于任何基于上下文的类,例如在ListView项中,但它主要用于活动。