Android: Cast View To View
Solution 1:
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.
Solution 2:
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
MyViewview= (MyView)findViewById(R.id.relative_layout_view);
Solution 3:
Why not just do
MyViewview= (MyView) findViewById(R.id.relative_layout_view);
Solution 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.
Post a Comment for "Android: Cast View To View"