What does the context parameter do in Android and how to determine it?

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

I see that some people use this as an argument, namely new LinearLayout(this) , but I don’t understand what this argument really is, and I would appreciate it if someone could give me a little guidance as to what to enter as an argument.

 LinearLayout layout = new LinearLayout(context); 

What should be the context ? How to identify it? What does it do? What value should be assigned?

+4
source share
2 answers

Easy way

just declare a variable as shown below

 private Context context; 

and onCreate (), assign its value as shown 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 calling getApplicationContext (), getContext (), getBaseContext () or this (when in the activity class).

+4
source

Context is an abstract class whose implementation is defined by the Android system. This helps to use the resources of the application, run events, broadcast and much more.

It tells the compiler which context action or application your application belongs to that you want to show. Basically we give an activity context when initializing a view.

 LinearLayout layout = new LinearLayout(ActivityName.this); 

or you can initialize the variable at the beginning of this action, for example

 private Context context; //in activity class context=ActivityName.this; 
0
source

Source: https://habr.com/ru/post/1479484/


All Articles