简体   繁体   中英

Why does an Android Button() created in the java code have to use (this) as the context?

I can create a button in Eclipse using Button button = new Button(); (which comes from the java.awt import). But how come in Android Studio, if I create a java code button using Button button = new Button() (which comes from the android.widget import), I get an error saying "cannot resolve constructor Button()" without using the (this) context?

Does this simply come down to a difference in how the Button() method is defined in the java.awt library and the android.widget library?

Just look at the doc , there is no constructor that takes no parameters. You must at least provide a Context .

The button needs an Android Activity as its context so as it knows where to exist. "this" is referring to the activity which is creating the button. If you have multiple activities running, it would also be valid to pass one of the other activities in as the context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM