简体   繁体   English

“布局”是否与 Android Studio 中的“布局资源”相同? 如何以编程方式创建 XML 布局资源?

[英]Is "layout" the same as "layout resource" in Android Studio? How can I programmingly create an XML layout resource?

I am really confused by these two concepts.我真的被这两个概念搞糊涂了。 I have known "layout resource" refer to some XML format files such as "activity_main.xml", and inside an XML file there is a layout.我知道“布局资源”指的是一些 XML 格式文件,例如“activity_main.xml”,并且在 XML 文件中有一个布局。 So "layout" and "layout resource" may be different, I assume.所以“布局”和“布局资源”可能不同,我想。

Today when I am using inflate (int resource, ViewGroup root, boolean attachToRoot) , I don't know how I can get the ID of the "resource" (aka the XML file) , because I just programmingly create a new layout for ListView to display items, and I can only get the ID of the new layout by using mylayout.setId(View.generateViewId()) .今天,当我使用inflate (int resource, ViewGroup root, boolean attachToRoot) ,我不知道如何获取“资源”(又名 XML 文件)的 ID,因为我只是以编程方式为 ListView 创建了一个新布局显示项目,我只能使用mylayout.setId(View.generateViewId())获取新布局的 ID。 But I don't know the ID of the "resource", since I never create an XML file.但我不知道“资源”的 ID,因为我从未创建过 XML 文件。 Is the ID of a layout equal to the ID of its XML file?布局的 ID 是否等于其 XML 文件的 ID?

So the question is here: when I only create a layout programmingly, how can I get its XML file?所以问题来了:当我只以编程方式创建布局时,如何获取其 XML 文件? Should I create a XML file rather than a layout?我应该创建 XML 文件而不是布局吗? If so, how can I make a new XML file programmingly?如果是这样,我如何以编程方式制作新的 XML 文件?

You can directly access the id of your xml file through: int id = R.layout.activity_main您可以通过以下方式直接访问您的 xml 文件的idint id = R.layout.activity_main

Note that this id is associated with the xml file itself.请注意,此id与 xml 文件本身相关联。 To access the id of a specific view within your layout file, replace layout with id : R.id.my_view_id .要访问您的布局文件中的特定视图的ID,替换layoutidR.id.my_view_id

For example, if you want to inflate my_layout.xml , you can pass R.layout.my_layout in the resource parameter of inflate (int resource, ViewGroup root, boolean attachToRoot) .例如,如果你想膨胀my_layout.xml ,你可以在my_layout.xml inflate (int resource, ViewGroup root, boolean attachToRoot)resource参数中传递R.layout.my_layout

When you're inflating a layout at run-time, you are using an existing xml file to create your layout.当您在运行时扩充布局时,您是在使用现有的xml 文件来创建您的布局。 A layout resource is a layout . layout resource是一个layout Layout is just an abstraction to represent your UI.布局只是代表您的 UI 的抽象。 It does not refer to anything specific.它不涉及任何特定内容。

Also, you cannot 'create' an xml layout programmatically (rather you shouldn't) to generate your UI at run-time.此外,您不能以编程方式“创建” xml 布局(而不是您不应该)以在运行时生成您的 UI。 But, you can create a view or a set of views contained within a ViewGroup programmatically.但是,您可以以编程方式创建一个视图或一组包含在ViewGroup的视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM