Casting for a button is superfluous - why?

I just stumbled upon this interesting post from the compiler, and I don't know why this is happening. Here is a case

Example 1

Button test = (Button) findViewById(R.id.someButtonId); test.setOnClickListener(this); 

Example 2

 findViewById(R.id.someButtonId).setOnClickListener(this); 

In the first example, I need to pass the object returned by findViewById to Button . In the second example, I do not need to throw the returned object, because I did not use another object of the Button class. If I try to transfer it through

 ((Button)findViewById(R.id.someButtonId)).setOnClickListener(this); 

I will get a warning Casting findViewById(R.id.someButtonId) to Button is redundant .

Why is this happening? I am not trying to remove the throw warning. I want to know the logic of this and why casting is not needed unless I try to initialize another object with the object returned by findViewById .

+8
android casting findviewbyid button
source share
5 answers

The reason you get this is because findViewById returns a View , and this class already defines the setOnClickListener method. This means that even without completing the throw, you can set the listener. Thus, your throw is redundant.

+6
source share

findViewById () always returns a View, which is the parent of all views, such as ImageView, Button ...

setOnClickListener is a method of the View class. This way you can catch click events simply without dropping it on the Button. I think that only this speaks of redundancy.

+2
source share

The reason for this is that in Example 1, you obviously need to find the button because you assign it to the Button variable.

OnClickListener is designed for any type of view, so you do not need to pass it to a specific subclass of View to install OnClickListener on it.

+2
source share

This is because you do not have to select the View in the Button to call setOnClickListener , which is defined in the View . It is enough to do findViewById(R.id.someButtonId).setOnClickListener(this);

+1
source share

I assume that setOnClickListener () is a method in a view, not a Button, and therefore yep: casting is redundant.

0
source share

All Articles