Button btn = new Button(this); what is the use of “this” in this context…?

ε祈祈猫儿з 提交于 2020-01-02 13:47:15

问题


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....??


回答1:


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




回答2:


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.




回答3:


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)



来源:https://stackoverflow.com/questions/6922765/button-btn-new-buttonthis-what-is-the-use-of-this-in-this-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!