这个任务有什么问题?

时间:2012-05-23 10:26:13

标签: android view

我已经定义了类似XX的类:

   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);

    }

}

在我的代码中我写道:

RelativeLayout v = (RelativeLayout) this.findViewById(R.id.switch_TCMyTB);
XX x = (XX) v;  //<----- crashes here

但它与作业崩溃了。我假设因为XX扩展了View我可以将视图(RelativeLayout)分配给XX对象。

但它崩溃了。作业有什么问题?

编辑:

我将extends View更改为extends RelativeLayout。还将View v更改为RelativeLayout v。 但我仍然得到一个classCastException .. ????为什么呢?

虽然

RelativeLayout r = (RelativeLayout) v; 

当然可行。

2 个答案:

答案 0 :(得分:0)

由于我并不完全熟悉自定义组件,所以我只是试着做一个例子。 我不能回答你的问题,为什么它不会工作。如果我的示例不适合您,则需要提供logcat。

我创建了一个自定义类:

public class TestLayout extends RelativeLayout {

    public TestLayout(Context context) {
        super(context);

    }

    public TestLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    public TestLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
}

这个类在com.test.cc包中

在XML布局中,我使用

    <com.test.cc.TestLayout 
    android:layout_width="10dip"
    android:layout_height="10dip"
    android:id="@+id/testLayout"    
    />

在此示例布局中.. TestLayout是LinearLayout的子级。 如果它是xml布局中的最高级别组件,则添加xmlns:android="http://schemas.android.com/apk/res/android"

然后在活动中:

//Called in onCreate mthod of an activity.    
setContentView(R.layout.test); //make sure you call this first
TestLayout l = (TestLayout)findViewById(R.id.testLayout);

对我来说这很好。

这是在2.2和3.2设备上测试的。

因此,请确保先调用setContentView(...),然后创建布局对象。 还要确保在xml中确定包是对的。虽然如果这是错误的,你会得到一个不是foudn异常的课程

EDIT ||

我试过这个:

RelativeLayout l = (RelativeLayout)findViewById(R.id.testLayout);
TestLayout tl = (TestLayout)l;

它也运行良好,没有任何例外。所以我认为问题出在其他地方。也许包名称错误或其他什么。

答案 1 :(得分:0)

以下代码在没有ClassCastExceptions的情况下运行 所以我的猜测是错误可能在于XML。

public class Test {

  public static void main(String[] args) {
    B b = new B();
    Object o = b;
    A a = (A) o;
    B b2 = (B) a;
    System.out.println("done");
  }

  public static class A /* extends Object */ {
  }

  public static class B extends A {
  }
}