-3

Context is used on several place such as in activity. But why we use context in Linear Layout? Whats the main reason to use it? LinearLayout layout = new LinearLayout(context);

Maroof
  • 11
  • 4

2 Answers2

2

In general, the Context you hand any View in Android is almost always an Activity. Like 99.9% of the time. However, there are cases where that's not what you want to pass. Such cases are those when, perhaps you're building part of the UI away from an Activity to be dropped into place later. You might not know what activity this will be attached to.

There are good reasons to make sure it is always the activity however, as is described in this article. For example, utilizing Activity makes sure the theme remains consistent.

Since a View does not need an activity, per say, to be created, we don't need to hand the Activity. Thus, the constructor only takes Context. This is a good example of ISP (The Interface Segregation Principle), in that, we're limiting the scope of what the View can access safely (what methods it can call on Context). We also increase the flexibility of the View API, because we don't require an Activity to instantiate views.

Alex Hart
  • 1,663
  • 12
  • 15
1

Activity isa Context as you can see in this.

A Context lasts the entire time your app is running while an Activity stops after your Activity ends. If the Activity ends before the LinearLayout object in your code, then a memory leak will happen since there is still a reference to that Activity.

PrMi
  • 75
  • 6