Search code examples
androidsetcontentview

Android Studio onCreate setContentView


I started a blank project and modified the onCreate by adding the below but the button is not being created because I can not see it in the design view. What am I doing wrong, I expected to see the button with its text as indicated.

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

Many thx


Solution

  • Since you are creating a layout through code, you will not see it in the XML view. If you build and run the app, you should see the Button appear.

    If you would rather see the Button in the XML view, you should modify the main_layout.xml to look like the following:

    <?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>
    

    You can get a reference to this Button in your Java code by using the following code after calling setContentView():

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