问题
From AppCompatButton reference page:
This will automatically be used when you use Button in your layouts. You should only need to manually use this class when writing custom views.
I'm casting a normal Button
to AppCompatButton
, so that I can use setSupportBackgroundTintList
method:
AppCompatButton button = (AppCompatButton) findViewById(R.id.normalButton);
button.setSupportBackgroundTintList(ColorStateList.valueOf(tintColor));
It builds and runs without any problem, but Android Studio 1.4 gives me the annoying red highlight on casting line:
Unexpected cast to AppCompatButton: layout tag was Button
Any ideas?
回答1:
It looks like a bug in the IDE type checking - Button is direct ancestor of AppCompatButton, so casting to AppCompatButton should be okay. I believe you can safely call it like this:
Button button = (Button) findViewById(R.id.normalButton);
((AppCompatButton)button).setSupportBackgroundTintList(ColorStateList.valueOf(tintColor));
or better
((TintableBackgroundView)button).setSupportBackgroundTintList(ColorStateList.valueOf(tintColor));
If you use Butterknife, everything works as expected without any warning:
@Bind(R.id.normalButton)
AppCompatButton button;
来源:https://stackoverflow.com/questions/33495164/unexpected-cast-to-appcompatbutton-layout-tag-was-button