2016-08-09 26 views
1

我想動態地從Java構建一個視圖,我很困惑爲什麼這不起作用。TextView沒有出現在RelativeLayout中

TextView displayText根本沒有顯示在屏幕上。我不明白爲什麼它不會像用戶輸入他們的名字那樣。

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     RelativeLayout ceriLayout = new RelativeLayout(this); 

     Button genButton = new Button(this); 
     genButton.setText("Press here"); 
     genButton.setId(0); 

     TextView displayView = new TextView(this); 
     displayView.setText("What is going to go here huh"); 
     displayView.setId(1); 

     EditText nameView = new EditText(this); 
     nameView.setText("Enter your name"); 
     nameView.setId(2); 

     RelativeLayout.LayoutParams button = new RelativeLayout.LayoutParams(
       RelativeLayout.LayoutParams.WRAP_CONTENT, 
       RelativeLayout.LayoutParams.WRAP_CONTENT 
     ); 

     RelativeLayout.LayoutParams name = new RelativeLayout.LayoutParams(
       RelativeLayout.LayoutParams.WRAP_CONTENT, 
       RelativeLayout.LayoutParams.WRAP_CONTENT 
     ); 
     RelativeLayout.LayoutParams display; 
     display = new RelativeLayout.LayoutParams(
       RelativeLayout.LayoutParams.WRAP_CONTENT, 
       RelativeLayout.LayoutParams.WRAP_CONTENT 
     ); 

     button.addRule(RelativeLayout.CENTER_HORIZONTAL); 
     button.addRule(RelativeLayout.CENTER_VERTICAL); 

     display.addRule(RelativeLayout.CENTER_HORIZONTAL); 
     display.addRule(RelativeLayout.ABOVE, nameView.getId()); 

     name.addRule(RelativeLayout.CENTER_HORIZONTAL); 
     name.addRule(RelativeLayout.ABOVE, genButton.getId()); 



     ceriLayout.addView(genButton, button); 
     ceriLayout.addView(nameView,name); 

     setContentView(ceriLayout); 

    } 
} 
+2

哇,慢下來的人。你是否在代碼上設計你的整個佈局?你知道你可以使用XML文件作爲佈局嗎? –

+0

'ceriLayout.addView(displayView ...'?它在哪裏? –

回答

2

您並未將displayView添加到您的ceriLayout中。這就是爲什麼它沒有出現。

一個忠告:請嘗試學習寫作裏面.xml佈局文件你View組件和設置這些佈局爲活動內容的意見。

相關問題