Java 按 id 查找布局
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19879909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding layouts by id
提问by Sochimickox
Noob here.
菜鸟在这里。
I am trying to spawn an image on a button click, in order to do that I took some code from this question: How do I create an ImageView in java code, within an existing Layout?I used the code from the first answer, but In the line:
我试图在单击按钮时生成一个图像,为了做到这一点,我从这个问题中获取了一些代码:How do I create an ImageView in java code, within an existing Layout? 我使用了第一个答案中的代码,但在行中:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.RelativeLayout01);
I don't know what to put instead of "RelativeLayout01", or how to have a layout in "id"
我不知道用什么代替“RelativeLayout01”,或者如何在“id”中设置布局
Thanks in advance
提前致谢
采纳答案by Josh
findViewById()
is a method you call on a view you've already inflated from an XML file (see this questionfor a little more detail on inflating views; also, the documentation for findViewById
).
findViewById()
是一种调用已从 XML 文件膨胀的视图的方法(有关膨胀视图的更多详细信息,请参阅此问题;另外,文档findViewById
)。
The "RelativeLayout01" in this example refers to an id set on the main layout in the XML file related to the Activity
that contains the click listener you're writing. It's just a placeholder; set an id on the main layout in your Activity
's XML file, and use that id in your code to place the image.
本示例中的“RelativeLayout01”指的是在与Activity
包含您正在编写的点击侦听器的相关的 XML 文件中的主布局上设置的 id 。它只是一个占位符;在您Activity
的 XML 文件的主布局上设置一个 id ,并在您的代码中使用该 id 来放置图像。
Also, if you haven't already, read the documentation on XML layouts; that should clear up a few things as well. The android:id
attribute (see the sample XML file; the attribute can be applied to any element) is the one relevant to your question.
另外,如果您还没有,请阅读有关 XML 布局的文档;这也应该澄清一些事情。该android:id
属性(见示例XML文件,该属性可以应用到任何元素),是有关您的问题之一。
回答by Esqarrouth
After you type R.id.r press CTRL+space on eclipse, it will try to autocomplete, if you see your variables in the list, then select them, if not then you didn't add them to XML.
键入 R.id.r 后,在 eclipse 上按 CTRL+space,它会尝试自动完成,如果您在列表中看到您的变量,则选择它们,如果没有,则您没有将它们添加到 XML。