2015-02-07 76 views
0

我開始了一個空白項目,並通過添加下面的代碼來修改了onCreate,但沒有創建按鈕,因爲我在設計視圖中看不到它。我做錯了什麼,我希望看到按鈕的文本如所示。Android Studio onCreate setContentView

Button b = new Button(this); 
b.setText("Hello Button"); 
setContentView(b); 

許多THX

+0

你運行一個設備或模擬器上這個項目? AFAIK設計視圖是基於xml的佈局 – 2015-02-07 22:35:37

回答

0

因爲要創建通過代碼的佈局,你不會看到它在XML視圖。如果您構建並運行該應用程序,則應該看到出現Button

如果你寧願看到XML鑑於Button,您應該修改main_layout.xml看起來像下面這樣:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <Button 
     android:id="@+id/button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="I am a Button"/> 

</LinearLayout> 

您可以通過在Java代碼中得到這個Button參考下面後的代碼調用的setContentView():

Button button = (Button) findViewById(R.id.button);