我的应用程序有一个浮动操作按钮,但它需要支持KitKat(API 19)。对于浮动操作按钮,我默认使用ImageButton
并将其(在布局中)替换为API 21或更高版本的真实FloatingActionButton
。
在我的活动中,我有代码来获得晶圆厂......
ImageButton mAddProject;
...
mAddProject = (ImageButton) findViewById(R.id.new_project_fab);
当然,这在Android 20或更低版本中运行良好,但在Android 21或更高版本中运行时,会抛出错误
Caused by: java.lang.ClassCastException: android.support.design.widget.FloatingActionButton cannot be cast to android.widget.ImageButton
doc表示FloatingActionButton
已从ImageButton
延长。我想这可以让我把它投到ImageButton
。我想我错了,不明白投射是如何运作的。
是否可以将FloatingActionButton
投射到ImageButton
?
答案 0 :(得分:2)
铸造实际上正在发挥作用。它只是按钮不存在。我认为以下代码应该有效:
FloatingActionButton mAddProject = (FloatingActionButton) findViewById(R.id.new_project_fab);
ImageButton mAddProjectImageButton = (ImageButton) mAddProject
由于此代码不会在API 19下运行,我建议如下:
我建议您以编程方式添加按钮。您应该检查版本,无论何时是API21 +,您都要添加FAB。只要它是20-,就可以添加ImageButton。通过这种方式,您可以确保使用正确的按钮来处理正确的API。
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP){
// Add the FAB button
} else{
// Add the ImageButton
}