jean-claude91
jean-claude91

Reputation: 167

LinearLayout findViewById problem - crash

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?

Upvotes: 13

Views: 33868

Answers (2)

jethro
jethro

Reputation: 18743

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"

Upvotes: 13

Jason Rogers
Jason Rogers

Reputation: 19344

You not loading a layout

you need to load on xml layout before using the findViewById

setContentView(R.layout.aLayout);

Upvotes: 3

Related Questions