Button btn = new Button(this);
btn.setText(“This is a Button”);
btn.setLayoutParams(params);
What will happen if we don't pass "this" as context reference to the Button..开发者_如何学C..??
Context is interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
Button is also resource of application so if you want to create button or any widget then you have to pass Context in constructor of widget.
for more details
http://developer.android.com/reference/android/content/Context.html
I don't know android sdk but usually parameter passed to constructor of a control is either parent or owner (sometimes it is not the same, for example in Borland's VCL parent is an control that child control is placed in, but owner is control that takes care of proper disposal of resources).
What would happen if you did not pass 'this' into constructor? either Button would not be visible (because nothing will call its Draw or whatever method is used to draw a controls on android) or you will have some kind of an exception thrown.
If you don't pass context to Button constructor you will get no Button instance wile there is no empty argument Button constructor. http://developer.android.com/reference/android/widget/Button.html#Button(android.content.Context)
精彩评论