如何摆脱Android Studio上的可疑通话警告?

gfp*_*eco 6 java android warnings casting button

在我的代码中,我有一个ArrayList<Buttons>名为的字段mButtons.这些按钮中的每一个都调用(在XML中)相同的onClick功能onButtonClick.该函数如下所示:

public void onButtonClick(View view) {
    int buttonIndex = mButtons.indexOf(view);
}
Run Code Online (Sandbox Code Playgroud)

但Android Studio一直在警告我Suspicious call to 'ArrayList.indexOf'.

好吧,我就先铸造摆脱viewButton.然后警告改为Casting 'view' to 'Button' is redundant.

好吧,我试图改变函数签名来接收一个Button而不是一个View.但现在我对每个Button声明(XML)都有一个警告:Method 'onButtonClick' on '...Activity' has incorrect signature.

我真的在考虑添加,//noinspection SuspiciousMethodCalls因为它似乎没有解决方法.

如果有人知道如何摆脱它,我将不胜感激.

Pau*_*ton 7

你可以Button在之前施放到线上.

Button button = (Button) view;
int buttonIndex = mButtons.indexOf(button);
Run Code Online (Sandbox Code Playgroud)


小智 5

作为一个额外的答案,您只需要将呼叫包装在checkof实例中

if (view instanceof Button) {
    buttonIndex = mButtons.indexOf(button);
}
Run Code Online (Sandbox Code Playgroud)

基本上,可疑电话是在说“无法保证这是一个有效的对象”

(很抱歉,回复缓慢,我在寻找答案时碰到了这个问题,我认为提供替代解决方案是最好的)