3

I'm new to Android and I'm working through some exercises on using various views. One such example is:

    TextView messageView = (TextView) findViewById(R.id.message);

My question is this: what would be the benefit of casting TextView? My IDE tells me that casting the method is redundant. Are there any use cases where I would want to cast in this way?

Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59
ProgRockMicky
  • 101
  • 1
  • 9
  • which android-studio version are you using – Sudheesh R Oct 27 '17 at 14:59
  • The reason why you get this is because findViewById returns View and this class already defines the method setOnClickListener. This means that even without doing the cast you can set the listener. Thus your cast is redundant. – Sudheesh R Oct 27 '17 at 15:00

1 Answers1

5

Before API level 26, the method findViewById returned the reference of View class. So you needed to cast it.

//old signature
public View findViewById(int id){
    //
}

But starting from API level 26, it has been updated and it returns subclass of View using template so that you can assign the returned reference without casting.

//new signature
public <T extends View > T findViewById(int id){
    //
}

The example which you referred used the older API level while building the project, so you can see the casting there. It was compulsory earlier but is not necessary now. So you are getting the warning.

Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59