2013-06-01 140 views
0

我已經動態地添加了LinearLayout並將其添加爲TextView。現在我必須添加背景,按照我的要求格式化它們。所以我堅持幾個問題。這裏是我的代碼:動態添加布局屬性

LinearLayout parentLayout = (LinearLayout) findViewById(R.id.master); 
LinearLayout Linear1 = new LinearLayout(this); 
Linear1.setOrientation(LinearLayout.HORIZONTAL); 
Linear1.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
     LayoutParams.MATCH_PARENT)); 
Linear1.setId(1); 
TextView tvLeft = new TextView(this); 
tvLeft.setText("Hello"); 
tvLeft.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
     LayoutParams.WRAP_CONTENT)); 
Linear1.addView(tvLeft); 
parentLayout.addView(Linear1); 

我有幾個問題:

  • 我如何添加繪製資源爲我的背景?

我已經試過這樣:

Linear1.setBackgroundResource(getResources().getDrawable(R.drawable.gradient_pink)); 

我由編譯器收到錯誤消息:

在類型視圖的方法setBackgroundResource(INT)不適用於參數(Drawable)

  • 如何訪問元素的標識是實用的?
  • 如何設置width = 0dip?

請幫我解決這些問題。

回答

2

試試這個

Linear1.setBackgroundResource(R.drawable.gradient_pink); 

Linear1.setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient_pink)); 

如何訪問其ID設置務實的元素?

findViewById(yourid)本身

+0

SETID只需要整數。我已經寫了setId(1)我應該在findViewById中寫什麼? – NewUser

+0

findViewById也只接受int ...你應該給'findViewById(1)' – Pragnani

+0

上午努力設置width = xdp/height = ydp ..請幫助這裏.. – NewUser