为什么我无法将Sub类加载到xml布局中?

时间:2011-12-01 04:32:24

标签: android layout android-layout android-emulator subclass

在我的应用程序中,我的XML布局如下:

<RelativeLayout
        android:layout_width="fill_parent"     
        android:layout_height="fill_parent">     

        <View
            class="com.project.twsbi.FingerPaint$MyView"
            android:id="@+id/image"      
            android:layout_width="fill_parent"         
            android:layout_height="fill_parent"
            />
        </RelativeLayout>

MyView是FingerPaint Project的子类。

现在在Java文件中,我将处理这些资源,如下所示:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(new MyView(this)); // Edited
    setContentView(R.layout.main);
    display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();


    // ste resources to View of Paint
    View view = (View)findViewById(R.id.image);

    view = new MyView(this);
  }

现在问题是我得到了另一个视图但不是那个子类视图。

编辑: 做完上面后,我没有成功,然后我尝试了另一种方法:

我已经在该布局中创建了相对布局,并为该相对布局添加了内容视图但仍然不起作用,并给我空指针异常:

第二种技术的XML代码是:

    <RelativeLayout
        android:layout_width="fill_parent"     
        android:layout_height="fill_parent">     

        <RelativeLayout
            android:id="@+id/drawingLayout"     
            android:layout_width="fill_parent"     
            android:layout_height="fill_parent">

        </RelativeLayout>
</RelativeLayout>

实施的Java代码是:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(new MyView(this)); // Edited
    setContentView(R.layout.main);

    drawingLayout = (RelativeLayout)findViewById(R.id.drawingLayout);


    // ste resources to View of Paint
    //view = (View)findViewById(R.id.image);

    myView = new MyView(this);
    RelativeLayout innerLayout = new RelativeLayout(getApplicationContext());
    innerLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
    //drawingLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
    LayoutParams lp = drawingLayout.getLayoutParams(); // got nullPointer exception here
    //innerLayout.addView(view);
    //drawingLayout.addView(innerLayout);
    addContentView(myView, lp);
  }

所以,在上面做的两个我都无法获得子类的视图? 哪里我错了? 请帮帮我。 。 。 感谢。

1 个答案:

答案 0 :(得分:1)

如果您尝试在列出的布局中包含不同的布局(MyView),请查看包含和合并:http://developer.android.com/resources/articles/layout-tricks-merge.html