簡體   English   中英

Android Studio onCreate setContentView

[英]Android Studio onCreate setContentView

我啟動了一個空白項目,並通過添加以下內容修改了onCreate,但未創建按鈕,因為在設計視圖中看不到該按鈕。 我做錯了什么,我希望看到帶有指示文本的按鈕。

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

多謝

由於您是通過代碼創建布局的,因此您不會在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>

調用setContentView() 之后 ,可以使用以下代碼 Java代碼中獲得對此Button的引用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM