Joel
Joel

Reputation: 13

Where's the "new" keyword? Android Tutorial Woes

While working my way through the Android tutorials, I came across something I don't understand. It's probably extremely simple, but I just need an idea why it's this way.

In the tutorial: http://developer.android.com/resources/tutorials/views/hello-autocomplete.html

The tutorial seems to construct a new AutoCompleteTextView using:

AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);

I assume their using the constructor:

AutoCompleteTextView(Context context, AttributeSet attrs)

I think their AttributeSet is the "findViewById(R.id.autocomplete_country)"; while their context is the (AutoCompleteTextView). Is this right?

Also... where's the new keyword, the comma, and why is there a pair of parenthesis?

I always thought it'd have to be:

AutoCompleteTextView textview = new AutoCompleteTextView(context here, attrs here);

Where am I going wrong?!

Upvotes: 1

Views: 389

Answers (2)

Anthony Forloney
Anthony Forloney

Reputation: 91786

findViewById returns the View corresponding to the argument passed in, and you cast the View to be the object of whatever the type you are working with.

Button myButton = (Button) findViewById(R.id.button);
                     ^ casting   ^ returns the View of your button.

Upvotes: 4

Tom R
Tom R

Reputation: 6009

The quoted code is not constructing an object but "getting" it. What you are doing is calling a function which returns a reference to an already constructed object. In this case, the object was probably created when the XML Layout was inflated (in the onCreate(Bundle) method of you Activity usually). The code is fine.

findViewById(R.id.something)

returns a View object. It then has to be wrapped in order to acces it as an instance of any of View's subclasses.

Upvotes: 1

Related Questions