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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With