开发者

Java inheritance in Android

I am trying to use the code depicted in this thread How to check visibili开发者_StackOverflow社区ty of software keyboard in Android?

As you can see the author is using a class which inherits from LinearLayout. And later initialize the new instance as follows:

LinearLayoutThatDetectsSoftKeyboard mainLayout = (LinearLayoutThatDetectsSoftKeyboard)findViewById(R.id.main);

Is that possible?I am getting a ClassCastException. And as explains here to do a downcasting you first need to reference the parent to the child.


Yes thats possible. Did you declare the custom LinearLayout correctly in the main.xml layout? Something like:

<com.yourpackage.LinearLayoutThatDetectsSoftKeyboard></com.yourpackage.LinearLayoutThatDetectsSoftKeyboard>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜