My application has several activities, and lists of "start activity" buttons. I created a custom view for this. So that I don't need to deal with click handlers and switch statements, I can set a custom:start_activity=".OtherActivity"
attribute in the layout's XML file.
Sure, nice plan. But I have to provide error detection for that. The typed string in start_activity
must be a valid class name, and the class must be child of Activity
. OtherActivity
is a subclass of a class that is a subclass of AppCompatActivity
.
This is what I've tried:
String name = array.getString(R.styleable.MyView_start_activity);
if (name == null)
throw new IllegalArgumentException("name attribute must be set.");
final String className = context.getPackageName() + activity;
try {
Class<?> check = Class.forName(className); //, false, getClass().getClassLoader()); // create only at click later
if (!Activity.class.isInstance(check))
throw new IllegalArgumentException(className + " is not a valid activity.");
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(className + " is not a valid class.");
}
However, that isInstance
always returns false, so it throws the exception all the time. I've also tried isAssignableFrom
, and different argument/class variants. The given string is a valid class, ClassNotFoundException
isn't thrown, and in the debugger, I can see Activity
in check
's superclass tree. I have no idea, what am I doing wrong?