Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the context parameter do in Android and what should it be defined as?

Tags:

android

I'm very new to Android development and I'm trying to create a view, which can be easily done by alloc then initWithFrame ... in Obj-C with Cocoa Touch, but in Java it uses the new ..() method and I'm stuck with defining the variable context, the parameter for LinearLayout().

I see some people use this as argument, namely new LinearLayout(this), but I don't understand what this argument actually does and I would appreciate if someone can give me a little bit guidance regarding what to put into as the argument.

LinearLayout layout = new LinearLayout(context);

What should context be? How should I define it? What does it do? What value should I assign it to?

like image 485
Help - I need somebody's help Avatar asked May 07 '13 07:05

Help - I need somebody's help


1 Answers

Simple way is

just declare variable as below,

private Context context;

and onCreate() method, assign its value as below,

public void onCreate(Bundle savedInstanceState) 
{
     super.onCreate(savedInstanceState);
     context = this;
     ...
}

You can also assign in another way as follows,

context = getApplicationContext();

You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in the activity class).

like image 136
Lucifer Avatar answered Sep 29 '22 18:09

Lucifer