2013-04-10 183 views
1

我GOOGLE了幾個小時,但不能拿出一個解決方案...我發現了許多類似的問題和答案,但他們都沒有爲我工作。動態創建佈局

我想要做的事: 我有一種觀點,我用它來畫我的應用程序。 現在我想添加一個佈局「在我的當前畫布上」。佈局應該包含一個按鈕,每邊都有20px的邊距。我發現了類似下面的代碼的代碼片段,但屏幕上沒有任何反應。沒有按鈕。沒有。

這是我使用的代碼:

LinearLayout bottomBar = new LinearLayout(this); 
bottomBar.setOrientation(LinearLayout.VERTICAL); 

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
layoutParams.setMargins(20, 20, 20, 20); 

Button button = new Button(this); 
button.setText("text"); 
bottomBar.addView(button, layoutParams); 
bottomBar.draw(canvas); 

我在做什麼錯?

+0

我可能是錯的,但你在那裏裝上屏幕此佈局?像'setContentView'? – Sriram 2013-04-10 13:58:41

+0

setContentView用於我的視圖(在此代碼段中不可見)。爲了使佈局可見,我使用最後的draw-method。 – JustABit 2013-04-10 14:01:44

回答

3

您創建佈局LinearLayout bottomBar = new LinearLayout(this);的事實並不意味着它被連接到屏幕上。

另外,不要打電話給你的酒吧。將其包含在屏幕中之後,系統會爲您打電話。

讓我們說,例如,你的XML(即用的setContentView膨脹)有它的FrameLayout ID爲R.id.frame,那麼你可以做這樣的事情:

LinearLayout bottomBar = new LinearLayout(this); 
bottomBar.setOrientation(LinearLayout.VERTICAL); 

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
layoutParams.setMargins(20, 20, 20, 20); 

Button button = new Button(this); 
button.setText("text"); 
bottomBar.addView(button, layoutParams); 

FrameLayout frame = (FrameLayout) findViewById(R.id.frame); 
frame.addView(bottomBar); 

你看...你必須在已經在屏幕上的視圖組中調用'addView'。

或者,您可以撥打:setContentView(bottomBar);取代無論是在屏幕上通過bottomBar

+0

嗯,我想我知道我必須知道的,所以我會接受它作爲答案。謝謝! – JustABit 2013-04-10 14:29:03

0

您不提供寬度/高度爲您的LinearLayout,你不附加到您的看法。

+0

如何將它附加到我的視圖中?我只能將視圖附加到佈局,這不是我想要的。 – JustABit 2013-04-10 14:15:14