Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 863
jean-claude91 Avatar asked Mar 10 '11 17:03

jean-claude91


People also ask

What is meaning of findViewById in android?

FindViewById(Int32) Finds a view that was identified by the android:id XML attribute that was processed in #onCreate . FindViewById<T>(Int32) Finds a view that was identified by the id attribute from the XML layout resource.

What is Viewview findViewById?

view. findViewById() is used to find a view inside a specific other view. For example to find a view inside your ListView row layout. Your app crashes without it because the view you're searching for is inside rowView .

What is LinearLayout?

LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally. You can specify the layout direction with the android:orientation attribute. Note: For better performance and tooling support, you should instead build your layout with ConstraintLayout.

How do I use findViewById on android?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


1 Answers

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"
like image 174
jethro Avatar answered Sep 21 '22 19:09

jethro