Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding layouts by id

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:

    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"

Thanks in advance

like image 834
Sochimickox Avatar asked Nov 09 '13 17:11

Sochimickox


People also ask

What is the use of Find view by ID in Android?

FindViewById(Int32)Finds a view that was identified by the android:id XML attribute that was processed in #onCreate .

What is Android ID XML?

For example, when you specify an ID to an XML resource using the plus sign — in the format android:id="@+id/myView" —it means that a new ID resource with the name “myView” needs to be created, and if it does not exist, create a unique integer for it and add to R. java .

Where are the layout files placed in Android?

Layout files are stored in "res-> layout" in the Android application. When we open the resource of the application we find the layout files of the Android application. We can create layouts in the XML file or in the Java file programmatically. First, we will create a new Android Studio project named "Layouts Example".


1 Answers

findViewById() is a method you call on a view you've already inflated from an XML file (see this question for a little more detail on inflating views; also, the documentation for 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.

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.

like image 52
Josh Avatar answered Sep 24 '22 19:09

Josh