When declaring custom view in xml, what is the difference between declaring a View of a custom class, or declaring a completely custom view:
<LinearLayout>
<view class="packageName.MyView" android:id="@+id/myView" />
</LinearLayout>
and
<LinearLayout>
<packageName.myView android:id="@+id/myView" />
</LinearLayout>
?
I’ve created a subclass of EditText, and when instatiating it as View class=".." my Activity crashes with ClassCastException when trying to access MyView:
(MyView) myView = (MyView) findViewById(R.id.myView);
When declared as second option, everything works as expected.
I’m not 100% sure on this, but let me give it a go. A couple of things could be happening. The parser might not understand the
classattribute correctly (e.g. it thinks it is part of a stylesheet). I am not sure how the parser handles the class attribute, since I have never seen or used it (in fact, I’ve never seen the<View>tag used either). A better explanation, though, might be this: the parser is trying to down-cast yourViewintopackageName.myViewclass and fails (down-casting is always risky; up-casting is always safe).Regardless of what is happening, I would always use the second option you listed,
<packageName.myView android:id...>, instead of using the<View>tag. Reason being, it’s redundant to use the<View>tag. Everything in this xml file must be a view (LinearLayout, Button, TextView, etc. are all descendants of the View class).Hope that helps. If you’re really, really curious, you could always download the source code for the parser…