2011-06-16 25 views
2

我創建了一個自定義視圖。其中,一條線,一條文本視圖,另一條線。在底線之下,我想放置一個新的水平方向的線性佈局。當我運行它時,這個嵌套的線性佈局似乎根本不顯示出來。相反,我可以在底線下方看到測試按鈕。我究竟做錯了什麼?自定義視圖:嵌套linearlayout沒有顯示

public class MyView extends LinearLayout { 

     public MyView(Context context, Question question) { 
      super(context); 



    //  this.setLayoutParams(params); 
      this.setOrientation(VERTICAL); 
      this.setBackgroundColor(Color.WHITE); 
      LinearLayout.LayoutParams lineParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 2); 
      View topLine = new View(context); 
      lineParams.setMargins(0, 15, 0, 0); 
      topLine.setBackgroundColor(Color.argb(255, 0, 159, 218)); 
      topLine.setLayoutParams(lineParams); 

      this.addView(topLine); 

      LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 

      //Challenge Question 
      TextView questionText = new TextView(context); 
      questionText.setTextColor(Color.BLACK); 
      questionText.setTextSize(14); 
      questionText.setLayoutParams(params); 
      questionText.setGravity(Gravity.CENTER_HORIZONTAL); 
      questionText.setText(question.getQuestion()); 

      this.addView(questionText); 

      View bottomLine = new View(context); 
      bottomLine.setBackgroundColor(Color.argb(255, 0, 159, 218)); 
      bottomLine.setLayoutParams(lineParams); 


      this.addView(bottomLine); 

      LinearLayout innerLayout = new LinearLayout(context); 
      LinearLayout.LayoutParams innerLayoutParams = new LinearLayout.LayoutParams(300, LayoutParams.WRAP_CONTENT); 
      innerLayout.setLayoutParams(innerLayoutParams); 
      innerLayout.setBackgroundColor(Color.RED); 
      innerLayout.setOrientation(HORIZONTAL); 


      //TableLayout for the multiple choices 
      TableLayout tableLayout = new TableLayout(context); 
      LayoutParams tableLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    //  tableLayoutParams.weight = .8f; 
      tableLayout.setBackgroundColor(Color.RED); 
      tableLayout.setLayoutParams(tableLayoutParams); 


      innerLayout.addView(tableLayout); 
      this.addView(innerLayout); 

      Button button = new Button(context); 
      button.setLayoutParams(params); 
      button.setText("testing 123"); 
      this.addView(button); 
} 

請注意,我粘貼的代碼沒有添加到tablelayout的所有東西。我可能應該也粘貼了。但是當我這樣做的時候它也不起作用。但無論哪種方式,如果我將嵌套的linearlayout設置爲300寬度併爲其設置紅色背景顏色,我至少應該看到它,不是嗎?

回答

1

想想內部佈局的高度應該是多少。現在它是wrap_content幷包含一個TableLayout(沒有行),其高度也設置爲wrap_content。在內部佈局中似乎沒有任何東西給它一個高度尺寸,所以這可能是它沒有被顯示的原因。

嘗試以下會讓你的佈局可見:

LinearLayout.LayoutParams innerLayoutParams = new LinearLayout.LayoutParams(300, 300); 

更有效,你可以嘗試添加一些與真實的寬度/高度的TableLayout

還可以考慮用XML編寫佈局到better separate your application logic and the presentation

+1

是的,正如我所說的,當我向tablelayout添加內容時它沒有工作,但是我即將在xml中創建tablelayout並將其添加到我的自定義視圖中。它很高興能夠靈活地混合和匹配程序化視圖與基於xml的視圖 – LuxuryMode 2011-06-16 19:34:47