-6

(I am new to android programming) I've seen this piece of code which assigns a predefined button to variable b:

Button b = (Button) findViewById(R.id.button1);

It's all clear for me (to me?), but I just don't get one thing: what is that (Button)?!

hadizadeh.ali
  • 63
  • 1
  • 8

2 Answers2

2

(Button) is a typecast. Every widget that comes back from findViewById is a View. To treat it as a button, you must explicitly tell the compiler that it is a Button.

More information on findViewById here, in the Android documentation: http://developer.android.com/reference/android/app/Activity.html

elizzmc
  • 125
  • 9
  • Just to further explain to the poster: When you create a button in your layout, you know it's a button, but your program doesn't know it's a button. By casting it to a Button you're basically telling the compiler "I promise this will be a Button". Your program will probably crash if you're lying about it being a Button. – BooleanCheese Oct 07 '15 at 17:36
1

when you are calling findViewByID(...) it returns a View type. Button is a child class of View and by saying (Button) you are type casting it which will allow you to use the methods/functions in the Button class.

Shrey
  • 671
  • 7
  • 14