KIO
Kreative Ideen online
findViewById()

findViewById()

We can get references for our two GUI components using a method called findViewById(). This method takes the ID of the GUI component as a parameter, and returns a View object. You then cast the return value to the correct type of GUI component (for example, a TextView of a Button). Here’s how you’d use findViewById() to get a reference to the text view with an ID of brands:

//We want the view with an ID of brands
TextView brands = (TextVeiw)findViewById(R.id.brands);
//brands is a TextView, so we have to cast it as on

Once you have a view, you can access its methods
The findViewById() method provides you with a Java version of your GUI component.This means that you can get and set properties in the GUI component using the methods exposed by the Java class.
For example:
As you have seen, you can get a reference to a text view in Java using:
TextView brands = (TextView)
findViewById(R.id.brands);
When this line of code gets called, it creates a TextView object called brands. Your are then able to call methods on this TextView object. Let’s say you wanted to set the text displayed in the brands text view to “Gottle of geer”. The TextView class includes a method called setText() that you can use to change the text property. You use it like this:
brands.setText(“Gottle of geer”);

Take a closer look at how we specified the ID of the text view. Rather than pRass in the name of the view, we passed in an ID of the form R.id.brands. So what does this mean?
What’s R?

R.java is a special Java file that gets generated by Android Studio whenever you create or build your app. It lives within the app/build/generated/source/r/debug folder in your project in a package with the same name as the package of your app. Android uses R.java to keep track of the resources used within the app, and among other things it enables you to get references to GUI components from within your activity code.
R is a special Java class that enables you to retrieve reference to resources in your app.

If you open up R.java, you’ll see that it contains a series of inner classes, one for each type of resource. Each resource of that type is referenced within the inner class. As an example, R.java includes an inner class called id, and the inner class includes a static final brands value. Android added this code to R.java whe we used the code “@+id/brands” in our layout. The line of code:
(TextView) findViewById(R.id.brands);
uses the value of brands to get a reference to the brands text view.

Leave a Reply

Your email address will not be published. Required fields are marked *