问题应该就在人家 MainMenuView 是 extends ActivityActivity会做很多东西, 首先所有view要依附的Window和Surface都会在这里创建,这样你的view就会有实际的落脚点了(view只是个逻辑的东西,其要render到surface上的)。否则只是虚拟的东西(因为没有落脚点,就无法实例出一个真正的东西——画不出来).
Activity等源代码还没看过,不过其定义:
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks {
}我猜应该和这个 implements LayoutInflater.Factory 有极大关系。
Activity等源代码还没看过,不过其定义:
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks {
}我猜应该和这个 implements LayoutInflater.Factory 有极大关系。
View.inflate(this, R.layout.main, null);
其实是返回一个View(返回值你没使用,直接扔掉了),并不是inflat到你的MyView!
public static View inflate(Context context, int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}第一个参数是context, Activity是context, view不是, 因此第二种调用方法就不对。
inflate要使用activity中实现的 LayoutInflater.Factory
view中没有context,更没有 LayoutInflater.Factory。第一个调用中的this,通过继承关系,是一个MainMenuView->Activity->ContextThemeWrapper->ContextWrapper->Context你自己写的:MyView->View可能人家的命名方式误导你了, 如果人家将MainMenuView命名为MainMenuActivity,就不会有任何疑问了。
public class MyView extends Activity
已经给你返回一个view了,为什么还要把他再封装在一个View里呢?有些多此一举。布局文件只是View的另一种表现形式。
View本身他没有填充布局文件的接口(因为布局文件是View的另外一种表现形式,不需要再来填充).对于你这个有多个组件的,你可以用Layout类去封装,例如: public class RecentApplicationsBackground extends LinearLayout {
在xml文件中的使用:
<com.android.internal.policy.impl.RecentApplicationsBackground
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@drawable/recent_dialog_background"
或者用Code的直接使用。
public class MyView extends Activity
[/Quote]