0

I'm a newbie in Android development.

I have Eclipse with ADT (sdk version: 17 , Android 4.2).

I don't understand what is the difference between:

  • DEFINING a View (via visual editor provided by ADT or directly in the XML layout file corresponding to the current activity)

and

  • INSTANTIATING a View (PASSING THE CONTEXT AS PARAMETER) such as: TextView tv = new TextView(getContext()); (taken from : What is 'Context' on Android? , first asnwer)

and

  • INSTANTIATING a View (WITHOUT PASSING THE CONTEXT AS PARAMETER) such as: TextView tv = new TextView();

Thank in advance for any advice.

Kind regards

Community
  • 1
  • 1
dragonmnl
  • 14,578
  • 33
  • 84
  • 129

1 Answers1

2

To use your terminology:

When DEFINING a View in XML (or the ADT editor - which just creates the XML for you), it still needs to be inflated by a layout inflater. A layout inflater will INSTANTIATE the View(s) for you. This can be done behind the scenes - such as when you call Activity.setContentView(), or directly using View.inflate(). The inflater effectively just runs through the XML and instantiates all of the Views it contains.

When INSTANTIATING a View, you're giving it the Context so it has a reference to resources - so it can load images, strings, dimensions etc - plus other Android related functionality (which you can probably ignore for now).

You can't INSTANTIATE a View without the context.

nmw
  • 6,664
  • 3
  • 31
  • 32
  • Thank you. Would you be so kind to explain me also the difference between using setContentView() and inflate()? – dragonmnl Jan 05 '13 at 23:16
  • `setContentView()` sets the layout or `View` to put inside your `Activity`. `View.inflate` inflates (i.e. builds) a `View` hierarchy from the XML you provide and returns it, for you to do something else with (unless you pass a `ViewGroup` as a parent - in which case it puts the View hierarchy it builds inside the parent you provide). – nmw Jan 06 '13 at 07:22