从最近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项目等有用吗?
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
//more views
</androidx.constraintlayout.widget.ConstraintLayout>
在上面的代码中,工具:context的基本需求是默认情况下告诉布局文件与哪个活动或片段相关联。因此,您可以使用与Manifest文件中使用的相同的点前缀指定活动类名。
通过这样做,Android Studio将自动为预览选择必要的主题,你不必手动进行预览设置。我们都知道一个布局文件可以与几个活动相关联,但是主题是在Manifest文件中定义的,这些主题与您的活动相关联。因此,通过在布局文件中添加tools:context, Android Studio预览将自动为你选择必要的主题。
这是最好的解决方案:
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
根据developer.android.com
适用于:任何根<视图>
使用对象:Lint, Android Studio布局编辑器
此属性声明默认情况下该布局与哪个活动相关联。这使得编辑器或布局预览中需要活动知识的功能成为可能,比如预览中的布局主题应该是什么,以及当您从快速修复中制作这些内容时,在哪里插入onClick处理程序(图2)。
图2。onClick属性的快速修复仅在设置了tools:context时有效
您可以使用与清单文件中相同的点前缀指定活动类名(不包括完整的包名)。例如:
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity" >