Android: Cast View to View

删除回忆录丶 提交于 2021-02-17 03:23:15

问题


I have a class that extends View (MyView extends View)

In Activity I have next:

    View view = (View)findViewById(R.id.relative_layout_view);

    //here I have error because of cast
    MyView myView = view;

Why its asked me to add cast ?

P.S: I added cast and app is crashes.


回答1:


Use this way Just add in xml like

<YourPackage Name.MyView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/myview"
android:layout_gravity="center"
>   
</YourPackage Name.MyView>

and after that use in activity as given below

   MyView view = (MyView)findViewById(R.id.relative_layout_view);



回答2:


MyView is a View, but View is not necessarily a MyView, so you need to explicitly cast it.

If it crashes, it means that the view with the ID relative_layout_view is NOT of type MyView, you need to make sure what its type is in the layout XML.




回答3:


Why not just do

MyView view = (MyView) findViewById(R.id.relative_layout_view);



回答4:


simple answer is that you are down casting your view instance to MyView.

its not always safe to down cast any object to its subclass and that is why compiler forces programmer to explicitly typecast his object to subclass.

In your case, view is not of type MyView. and this is the reason compiler gives classCastException.

But if R.id.relative_layout_view was of type MyWiew, it would have not generated any exception.



来源:https://stackoverflow.com/questions/10598640/android-cast-view-to-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!