Unexpected cast to AppCompatButton: layout tag was Button

江枫思渺然 提交于 2019-12-24 12:03:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!