【问题标题】:Java inheritance in AndroidAndroid中的Java继承
【发布时间】:2011-07-09 13:13:04
【问题描述】:

我正在尝试使用此线程中描述的代码How to check visibility of software keyboard in Android?

如您所见,作者使用的是继承自 LinearLayout 的类。然后按如下方式初始化新实例:

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

这可能吗?我收到了 ClassCastException。正如here 解释的那样,要进行向下转换,您首先需要将父级引用到子级。

【问题讨论】:

    标签: java android inheritance casting


    【解决方案1】:

    是的,这是可能的。您是否在 main.xml 布局中正确声明了自定义 LinearLayout? 比如:

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

    【讨论】:

      【解决方案2】:

      只要您从findViewById(..) 获得的对象确实是LinearLayoutThatDetectsSoftKeyboard(或子类)的实例,转换就可以了。这显然不是由于抛出的异常(您确实需要捕获并打印它,因为它会指出演员表问题..)

      查看此(特别是考虑到您的声明“要进行向下转换,您首先需要将父级引用到子级。”)最后一条语句C c3 = (C) getO(); 与您的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
          }
      }
      

      结论:

      您在某种程度上存在配置问题,并且您的视图 (R.id.main) 不是 LinearLayoutThatDetectsSoftKeyboard

      【讨论】:

      • findViewById(R.id.main) 是一个线性布局。 LinearLayoutThatDetectsSoftKeyboard 的父类
      • 顺便说一句,在你的例子中,你是在做一个空对象的转换吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 2011-02-20
      • 2012-10-30
      • 2017-12-27
      相关资源
      最近更新 更多