0

我试图做的是在一个RelativeLayout中使用自定义视图(这是一个构造函数& onDraw方法)和一组控件,并将它们一起显示在FrameLayout中。我的代码目前正在添加叠加和崩溃与空指针执行,但如果我直接添加叠加和削减FrameLayout自定义视图的作品。Android - 带有需要构造函数的自定义视图的FrameLayout

FrameLayout layout = new FrameLayout(this); 
SampleView sv = new SampleView(this, objectA, objectB, ObjectC), RESULTS); 
RelativeLayout overlay = (RelativeLayout) findViewById(R.layout.analysis_overlay); 

layout.addView(sv); 
layout.addView(overlay); 

setContentView(layout); 

我假设有一个更好的方式来做到这一点,我已经看到了现有的XML中的FrameLayout的例子,但我没有看到反正设置通过该方法构造的......那么,有没有更好的方式做到这一点,仍然允许自定义视图有一个构造函数,或者我用我当前的代码搞砸了吗?

回答

1

您正在尝试查找布局资源的ID。相反,膨胀相对布局(布局资源),然后添加它。

FrameLayout layout = new FrameLayout(this); 
SampleView sv = new SampleView(this, objectA, objectB, ObjectC), RESULTS); 
RelativeLayout overlay = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.analysis_overlay, layout, false); 


layout.addView(sv); 
layout.addView(overlay); 

setContentView(layout); 
1
RelativeLayout overlay = (RelativeLayout) findViewById(R.layout.analysis_overlay); 
  • 你永远无法找到R.layout ID为任何东西。使用R.id

  • 使用ActivityfindViewById()时,您永远无法找到setContentView()之前的任何内容。

调用findViewById()在实际上包含要查找的叠加层的视图层次结构上。

如果您只是要扩充XML布局,请使用LayoutInflater

相关问题