java - 两种不同的参数类型(将对象转换为类型)

标签 java android object button imagebutton

我想调用一个方法,但参数可以是 Button 或 ImageButton。我使用不同的参数类型作为对象调用该方法两次。

在我的方法 attributesOfButton 中,我想像下面的代码一样分配相应的按钮类型。

private void memCheck()
{
    ImageButton imageButtonCam;
    Button buttonCamCo;

    attributesOfButton(imageButtonCam);
    attributesOfButton(buttonCamCo);
}

private void attributesOfButton(Object button) 
{
    Object currentButton;

    if (button instanceof ImageButton) 
    {
        currentButton = (ImageButton) button;
    } 

    if (button instanceof Button ) 
    {
        currentButton = (Button) button;
    } 

    // do something with button like:
    if (Provider.getValue == 1) {
        currentButton.setEnabled(true);
    }
}

但它不起作用。例如,如果我这样做:

currentButton.setEnabled(true);

我明白了

Cannot resolve method setEnabled(boolean)

最佳答案

您的对象 currentButton 仍被定义为 Object,因此即使您知道它是一个子类,您也不能在其上使用 Object 的方法以外的任何东西。您需要使用适当的类定义一个对象:

private void attributesOfButton(Object button) 
{
    if (button instanceof ImageButton) 
    {
        ImageButton currentButton = (ImageButton) button;
        // do stuff for ImageButton
    } 

    if (button instanceof Button ) 
    {
        Button currentButton = (Button) button;
        // do stuff for Button
    } 
}

关于java - 两种不同的参数类型(将对象转换为类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30803721/

相关文章:

java - 如何将 servlet 添加到 spring 框架 java web 应用程序?

java - 泛型和流 : How to make this into a `StreamTuple::new` statement?

java - 将java项目连接到mongodb数据库

android - Fragment Transition 和 Alpha 问题

c# - 如何对集合中所有对象的属性执行 .Max() 并返回具有最大值的对象

javascript - find() 无法识别 javascript 对象数组中的重复值

java - 我很困惑——这段代码总是有效吗?

android - flutter中实现自定义底部导航栏

android - Superpowered SDK尝试同时录制和播放

javascript - 在数组中查找带有值的对象键?