1

在我问我应该为我的项目使用 XML 还是 View 类之后,你告诉我,我应该在 XML 中做所有可能的事情,其余的使用一个类。你告诉我,用 XML 动画 Sprite 是不可能的,所以我想制作一个 View Class。我得到了谷歌“LayoutInflater”的提示,我做到了。

关于充气机的信息并不多,所以我访问了 android 的开发者数据库并试图了解它是如何工作的。

据我所知,您必须在主游戏活动的 onCreate 方法中添加一些内容(setContentView 必须是 mainXML)。

所以现在我在我的 mainXML 中创建了一个 LinearLayout 并将其称为“容器”,并将其作为一个称为“父级”的 ViewGroup。

现在我创建了一个全局变量“private View view”并写下了这一行:

view = LayoutInflater.from(getBaseContext()).inflate(new ViewClass(this), null);

现在的问题是你不能像这样膨胀一个类,我认为我做错了这整个膨胀的事情。

你有什么提示和技巧可以让我在我的 mainXML 中有一个 LinearLayout 并能够让我的视图类中的内容出现在其中吗?

编辑:

让它正常工作,但如果我现在开始游戏,什么都不会发生。

如果您有任何解决方案,请回答以下代码:

    super.onCreate(savedInstanceState);

    // inflate mainXML->
    View mainView = getLayoutInflater().inflate(R.layout.activity_game, null);
    // find container->
    LinearLayout container = (LinearLayout) mainView.findViewById(R.id.container);
    // initialize your custom view->
    view = new GameLayout(this);
    // add your custom view to container->
    container.addView(view);

    setContentView(R.layout.activity_game);

还有我的游戏布局:

public GameLayout(Context context) 
{
    super(context);     
}

@Override
protected void onDraw(Canvas canvas)
{
    canvas.drawColor(Color.BLACK);
}
4

1 回答 1

2

有两种方法可以解决这个问题。我将向您展示其中之一。onCreate(Bundle)在调用之前执行以下操作setContentView(...)

// inflate mainXML
View mainView = getLayoutInflater().inflate(R.layout.mainXML, null);

// find container
LinearLayout container = (LinearLayout) mainView.findViewById(R.id.container);

// initialize your custom view
view = new ViewClass(this);

// add your custom view to container
container.addView(view);

最后:

setContentView(mainView);

或者,您可以将自定义视图放在 mainXML 中:

<your.package.name.ViewClass
    android:id="@+id/myCustomView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    .... />
于 2013-08-16T18:11:45.780 回答