How to get rid of a suspicious call on Android Studio?

In my code, I have an ArrayList<Buttons> field named mButtons . Each of these buttons calls (in XML) the same onClick function onButtonClick . The function is as follows:

 public void onButtonClick(View view) { int buttonIndex = mButtons.indexOf(view); } 

But Android Studio warns me about Suspicious call to 'ArrayList.indexOf' .

Ok, I tried to get rid of it by clicking view on Button . Then the warning changed to Casting 'view' to 'Button' is redundant .

Well, I tried to change the function signature to get Button instead of view . But now I have one warning for each Button (XML) declaration: Method 'onButtonClick' on '...Activity' has incorrect signature .

I'm really considering adding //noinspection SuspiciousMethodCalls , since there seems to be no workaround for this.

I would appreciate it if anyone knows how to get rid of it.

+6
source share
2 answers

You can use the Button string earlier.

 Button button = (Button) view; int buttonIndex = mButtons.indexOf(button); 
+6
source

As an additional answer, you just need to wrap the call in instanceof check

 if (view instanceof Button) { buttonIndex = mButtons.indexOf(button); } 

Mostly a suspicious call says "There is no guarantee that this is a valid object to search for"

(Sorry for the slow answer, I got into this thread when looking for an answer, and I decided that the best option for an alternative solution)

+4
source

Source: https://habr.com/ru/post/986429/


All Articles