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

相關問題