Why do we always type cast in Android/Java?

前端 未结 3 1563
小蘑菇
小蘑菇 2021-01-04 10:47

I am writing an Android app and just was curious about why we must always type-cast in Android. I understand that we need to be sure of the type so that our code runs proper

3条回答
  •  一个人的身影
    2021-01-04 11:28

    In android - while writing java code you need to bring XML code inside Java.

    So we use R.id.drawer_layout is what we want to bring inside java which becomes findViewById(R.id.drawer_layout) which returns an Object.

    So we then assign it to a variable declared at top.

     private DrawerLayout mDrawerLayout;
    

    where DrawerLayout is a class in java android.

    mDrawerLayout = findViewById(R.id.drawer_layout);
    

    Since findViewById(R.id.drawer_layout) returns an object and we are assigning it to a variable we need to typecast by using

    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    

提交回复
热议问题