Android: Layout.addView() doesn't work

16,869

Solution 1

  LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);

In your xml file main xml layout android:id="@+id/mainLayout" 

Solution 2

You should set id for your root LinearLayout in main.xml like

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/mainLayout">

and then reference it as

LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);

instead of findViewById(R.layout.main);

Share:
16,869
Incinerator
Author by

Incinerator

Fullstack software engineer experienced in JavaScript, Java, Kotlin, Swift, Flutter/Dart, Python etc. I have been programming since 2003. Read more about me on Github or on my blog.

Updated on June 04, 2022

Comments

  • Incinerator
    Incinerator almost 2 years

    When I try to run the following code I get an error. The emulator gives me this error message and then the app force closes: The application has stopped unexpectedly. What is wrong?

    import edu.chl.dat255.bluebanana.R;
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    
    public class ProMan extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            LinearLayout layout = (LinearLayout) findViewById(R.layout.main);
    
            TextView t = new TextView(getApplicationContext());
            t.setText("Hello world");
            layout.addView(t);
        }
    }