gpt4 book ai didi

android - LayoutInflater 用于使用 xml 和 View 类

转载 作者:行者123 更新时间:2023-11-29 21:36:40 25 4
gpt4 key购买 nike

在我问我是否应该为我的项目使用 XML 或 View 类之后,你告诉我,我应该尽一切可能使用 XML 并为其余部分使用一个类。你告诉我,使用 XML 不可能为 Sprites 设置动画,所以我想制作一个 View 类。我得到了谷歌“LayoutInflater”的提示,我做到了。

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

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

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

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

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

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

对于在我的 mainXML 中使用 LinearLayout 并能够使我的 View 类中的内容出现在其中,您是否有任何提示和技巧可以帮助我?

编辑:

它可以正常运行,但如果我现在开始游戏,什么也不会发生。

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

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

最佳答案

有两种方法可以解决这个问题。我给你看其中一个。在调用 setContentView(...) 之前,在 onCreate(Bundle) 中执行以下操作:

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

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

<your.package.name.ViewClass
android:id="@+id/myCustomView"
android:layout_width="match_parent"
android:layout_height="match_parent"
.... />

关于android - LayoutInflater 用于使用 xml 和 View 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18279518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com