android - LayoutInflater 用于使用 xml 和 View 类

标签 android xml layout view

在我问我是否应该为我的项目使用 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/

相关文章:

php - 从 XML 文件中去除所有标签

java - 适配器未连接,布局已跳过

html - Flexbox 布局 - 四个 DIVS + Fullheight DIV

android - WifiManager.calculateSignalLevel(RSSI, 5) 问题

android - 构建大小大于 100 Mb 的 android 应用程序

c# - 在 XDocument 中查找元素?

zend-framework - 如何在一个 Zend_Form 中连续放置 2 个按钮

android - 我无法从 Android GCM 获取注册 ID

android - 我可以模拟 Wi-Fi 连接来测试 Wi-Fi Direct 吗?

JAXB 说明的 Java Oracle 文档(什么是 Java 属性特性)?