[英]Can I cast FloatingActionButton to ImageButton in Android?
My app has a floating-action-button, but it needs to support KitKat (API 19). 我的应用程序具有浮动操作按钮,但它需要支持KitKat(API 19)。 For the floating-action-button, I use an
ImageButton
by default and swap it (in the layout) for the real FloatingActionButton
for API 21 or higher. 对于浮动动作按钮,我默认使用
ImageButton
并将其(在布局中)交换为API 21或更高版本的实际FloatingActionButton
。
In my activity, I have the code to get the fab as this... 在我的活动中,我有获取晶圆厂的代码,如下所示:
ImageButton mAddProject;
...
mAddProject = (ImageButton) findViewById(R.id.new_project_fab);
Of course, this works fine in Android 20 or lower, but when being run in Android 21 or higher, it throws an error 当然,这在Android 20或更低版本上可以正常运行,但是在Android 21或更高版本上运行时会引发错误
Caused by: java.lang.ClassCastException: android.support.design.widget.FloatingActionButton cannot be cast to android.widget.ImageButton
The doc says that FloatingActionButton
is extended from ImageButton
. 该文档说
FloatingActionButton
是从ImageButton
扩展的。 I imagine this would allow me to cast it to ImageButton
. 我想这会让我将其投射到
ImageButton
。 I guess I'm wrong and don't understand how casting works. 我猜我错了,不了解转换的工作原理。
Is it possible to cast FloatingActionButton
to ImageButton
? 是否可以将
FloatingActionButton
ImageButton
为ImageButton
?
The casting is actually working. 投射实际上正在工作。 It just is that the button does not exist yet.
只是该按钮尚不存在。 I think that the following code should work:
我认为以下代码应该有效:
FloatingActionButton mAddProject = (FloatingActionButton) findViewById(R.id.new_project_fab);
ImageButton mAddProjectImageButton = (ImageButton) mAddProject
Since this code won't run below API 19, I suggest the following: 由于此代码不会在API 19下运行,因此建议以下操作:
I would suggest that you add the button programmatically. 我建议您以编程方式添加按钮。 You should check the version and whenever it is API21+, you add the FAB.
您应该检查版本,并且只要是API21 +,就添加FAB。 Whenever it is 20-, you add the ImageButton.
只要是20-,就添加ImageButton。 This way you are sure that you have the correct button working for the correct API.
这样,您就可以确保正确的按钮适用于正确的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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.