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 .
android casting findviewbyid button
sandalone
source share