0

I wrote a method to get views by id in Android like this: E.g.

Button button = <Button>find(R.id.someId);

There is actually no need for < Button>. This is the method I wrote:

protected <T extends View> T find(int id){
    return (T) findViewById(id);
}

It works great, but the warning "Unchecked cast" bothers me. How could I get rid if it? Is this method save? I was inspired by Kotlin so much, that I wanted to create this nice little method to make the code prettier.

Sermilion
  • 1,920
  • 3
  • 35
  • 54

3 Answers3

1

You can try to use @SuppressWarnings("unchecked"), It is an annotation to suppress compile warnings about unchecked generic operations (not exceptions), such as casts

According to its Javadocs, it can go on local variables; this way, it doesn't even affect the entire method.

1

The warning is there because you don't know whether the View is really of the type T which confuses the normal android checks.

Why don't you simply do

protected View find(int id){
    return findViewById(id);
}

and then

Button button = (Button)find(R.id.someId);

to avoid the cast in the method and using generics.

This is equally short and will not result in this warning.

Slamper
  • 445
  • 3
  • 10
  • In your method you effectively do casting too which makes the whole thing pretty pointless. But I fully agree whith Lev who recommends using Butterknife. – Slamper Oct 10 '16 at 14:44
  • ok, I came up with this: protected T find(int id, Class type){ return type.cast(findViewById(id)); } – Sermilion Oct 10 '16 at 14:47
  • I mean, the whole point was avoid casing expression. so, this solution is actually what I wanted. I found it here: http://stackoverflow.com/questions/450807/how-do-i-make-the-method-return-type-generic – Sermilion Oct 10 '16 at 14:48
1

I came up with what I was looking for based on this answer: How do I make the method return type generic?

protected <T extends View> T find(int id, Class<T> type){ 
    return type.cast(findViewById(id)); 
}

It allows me to retrieve view like this:

Button button = find(R.id.someButton, Button.class);

which I think is nice. Thanks to @Lev for pointing out JakeWharton/butterknife , I ll definitely use it from now on.

Community
  • 1
  • 1
Sermilion
  • 1,920
  • 3
  • 35
  • 54