java参数类型不同_java – 两种不同的参数类型(将Object强制转换为Type)

我想调用一个方法,但参数可以是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,object,android,button,imagebutton

来源: https://codeday.me/bug/20190702/1359570.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值