The cast is fine as long as the object you get from findViewById(..)
is indeed an instance of a LinearLayoutThatDetectsSoftKeyboard
(or a subclass). And it clearly is not be due to the exception thrown (which you really need to catch and print as it will point out the cast issue ..)
Review this (specially given your statement "to do a downcasting you first need to reference the parent to the child.") That last statement C c3 = (C) getO();
is precisely equivalent to your LinearLayoutThatDetectsSoftKeyboard mainLayout = (LinearLayoutThatDetectsSoftKeyboard)findViewById(R.id.main);
package sof_6627310;
public class CastingAndInheritanceBasics {
/** a parent base class ala LinearLayout */
public static class P {}
/** a kind of P ala LinearLayoutThatDetectsKeyboard */
public static class C extends P {}
/** another kind of P and not a C */
public static class O extends P {}
/* a few functions all returning P references to an instance of P or a subclass */
static final P getNull() { return null ; }
static final P getO() { return new O(); }
static final P getP() { return new P(); }
static final P getC() { return new C(); }
@SuppressWarnings("unused")
public static final void main(String[] args) {
P p1 = getP();
P p2 = getC();
P p3 = getO();
C c1 = (C) getC(); // OK
C c2 = (C) getNull(); // OK
C c3 = (C) getO(); // compiles but runtime error
}
}
Conclusion:
You have a configuration issue at some level and your view (R.id.main
) is NOT a LinearLayoutThatDetectsSoftKeyboard
.