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?
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.
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 .
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With