I have defined a class XX like this:
public class XX extends RelativeLayout {
protected static final boolean DEBUG = true;
public XX(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public XX(Context context, AttributeSet attrs) {
super(context, attrs);
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->2"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
//getAttributes(context, attrs);
}
public XX(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->3"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
//getAttributes(context, attrs);
}
}
and in my code I write:
RelativeLayout v = (RelativeLayout) this.findViewById(R.id.switch_TCMyTB);
XX x = (XX) v; //<----- crashes here
but it crashes with the assignment. I assume the because XX extends View I can just assign the view (RelativeLayout) to an XX object.
But it crashes. What is wrong with the assignment?
EDIT:
I changed extends View to extends RelativeLayout. Also changed View v to RelativeLayout v.
But I still get a classCastException..???? Why?
While
RelativeLayout r = (RelativeLayout) v;
certainly works fine.
Since I’m not completely familiar with custom components, I just tried to make an example.
I can’t answer your question as to why it wont work. If my example won’t run for you, you will need to provide a logcat.
I create a custom class:
This class is in the package com.test.cc
In an XML layout I use
In this example layout.. TestLayout is a child of a LinearLayout.
Add
xmlns:android="http://schemas.android.com/apk/res/android"if its the highest level component in an xml layout.Then in the activity:
This runs fine for me.
This was tested on a 2.2 and 3.2 device.
So make sure you call setContentView(…) first and then create an object of the layout.
Also make sure in the xml deffinition the package is right. Although if this was wrong you would get an class not foudn exception
EDIT||
I tried running this:
And it also runs fine without any exceptions. So I assume the problem lies elsewhere. Maybe package name errors or something.