LinearLayout findViewById problem - crash

32,377

Solution 1

You have to set layout for your Activity from resources

setContentView(R.layout.my_layout);

Then you can call findViewById()

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_layout); // add this code
    LinearLayout ln = (LinearLayout) this.findViewById(R.id.linlay);
    ln.setBackgroundDrawable(getResources().getDrawable(R.drawable.wallpaper));
}

In your case you can simply set wallpaper in xml resource file by adding to LinearLayout

android:background="@drawable/wallpaper"

Solution 2

You not loading a layout

you need to load on xml layout before using the findViewById

setContentView(R.layout.aLayout);
Share:
32,377

Related videos on Youtube

jean-claude91
Author by

jean-claude91

Updated on April 26, 2020

Comments

  • jean-claude91
    jean-claude91 almost 4 years

    my problem is probably pretty simple. I have defined a LinearLayout in my layout.xml file and want to set the background drawable in code.

    layout.xml

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

    .java

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout ln = (LinearLayout) this.findViewById(R.id.linlay);
        setContentView(ln);
        ln.setBackgroundDrawable(getResources().getDrawable(R.drawable.wallpaper));
    }
    

    If I run the app it says the application has stopped unexpectedly. any ideas?

  • jean-claude91
    jean-claude91 about 13 years
    thanks for your answer, but i tried that before and it didn't work either. I know that i can set the background in the xml file but my real problem is a little bit more complex and i need to set the background in java for that. So is there another mistake?
  • jean-claude91
    jean-claude91 about 13 years
    alright :D I'm sorry i may have done some other thing wrong because with a new project is worked just like described. Big Thanks to you all.

Related