Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing background image based on orientation.

I have a simple problem that seems to have two simple solutions, neither of which work for me and i cant seem to understand why.

I want to have a portrait view background and an alternate landscape background for my layout. I placed the different images in the separate folders layout and layout-land respectively.

portrait = exactly what it should landscape = black screen

then i tried making a folder called drawable-land and placing the wide view background there. same result.

black when going to portrait.

Is there something im missing? This seems so simple and i cant understand what i could possibly be doing wrong.

Thanks in advance.

like image 327
TheRedStig Avatar asked Feb 06 '26 01:02

TheRedStig


1 Answers

To programmatically change your background depending on the orientation of the screen:

     @Override
     public void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);

     LinearLayout linearLayout = (LinearLayout)findViewById(R.id.layout);
     Resources res = getResources();
     Drawable portrait = res.getDrawable(R.drawable.portrait);
     Drawable landscape = res.getDrawable(R.drawable.landscape);

     WindowManager window = (WindowManager)getSystemService(WINDOW_SERVICE);
     Display display = window.getDefaultDisplay();
     int num = display.getRotation();
     if (num == 0){
         linearLayout.setBackgroundDrawable(portrait);
     }else if (num == 1 || num == 3){
         linearLayout.setBackgroundDrawable(landscape);
     }else{
        linearLayout.setBackgroundDrawable(portrait);
     }
    }

Try that out, I hope it helps!

like image 93
chRyNaN Avatar answered Feb 09 '26 09:02

chRyNaN