5

How to set background for all activities in adnroid application and keep it's aspect ratio?

I am using android:windowBackground in style, but I don't know, how to keep aspect ratio for my background image.

Is there only way to add ImageView with background for all activities manually?

Alexey Markov
  • 1,546
  • 2
  • 23
  • 41

2 Answers2

2

You could define your own base activity as an abstract class and make every other activity in your application extend from that:

abstract class BaseActivity extends Activity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        // this is a generic way of getting your root view element
        View rootView = (View) findViewById(android.R.id.content);
        rootView.setBackgroundDrawable(getResources().getDrawable(R.drawable.your_image));        
    }
}

Then you should extend that in your desired activity:

public class YourActivity extends BaseActivity
Rogério Peixoto
  • 2,176
  • 2
  • 23
  • 31
2

You might be able to set the background in the styles.xml

<style name="AppTheme.FullBackground" parent="AppTheme">
    <item name="android:background">#757575</item>
</style>

(Where AppTheme might be a theme you already defined, and I just used a grey color there, but it can be a drawable)

Then add to your Manifest

<activity 
    android:name=".FooActivity"
    android:theme="@style/AppTheme.FullBackground">
</activity>

Since you have to add activities to the Manifest anyway, this is a good way to check if all the activities have the background. You, of course, could still extend the BaseActivity and only have the BaseActivity class maintain the theme setting.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Well, I've **already** use `android:background` to set background image, but it's strethced and ugly – Alexey Markov Jun 13 '16 at 22:01
  • Your question has windowBackground, not background, but I see what you're saying, and I found this post http://stackoverflow.com/questions/5902230/how-to-implement-an-androidbackground-that-doesnt-stretch – OneCricketeer Jun 13 '16 at 22:15
  • "background" attribute used for all views you must use "windowBackground" instead of background if you want work for activities only. – Hadi Ahmadi Mar 26 '20 at 03:37