【发布时间】:2013-08-16 18:03:24
【问题描述】:
在我问我应该为我的项目使用 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 并能够使我的 View Class 中的内容出现在其中吗?
编辑:
让它正常工作,但如果我现在开始我的游戏,什么都不会发生。
这里是代码,如果你有任何解决方案请回答:
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);
}
【问题讨论】:
-
使用活动上下文而不是
getBaseContext()。new ViewClass(this)是什么? -
这是一个类,我想在其中对 LinearLayout 的输入进行编码(我知道把它放在那里很愚蠢,但我想让你知道,我正在尝试做什么)跨度>
-
您的 ViewClass 是否扩展视图?
-
是的,但 inflate(int, ViewGroup) 不接受。