Android实现屏幕背景的自动切换

1. 在drawable-mdpi文件夹中存放bg_v(竖屏背景图片)和bg_h(横屏背景图片)。

2. 

 1 public class AndroidHelper {
 2     
 3     public AndroidHelper() {
 4         
 5     }
 6     //获取屏幕方向
 7     public static int ScreenOrient(Activity activity) {
 8         int orient = activity.getRequestedOrientation();
 9         if (orient != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE && orient != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
10             //宽<高为竖屏,反之为横屏
11             WindowManager windowManager = activity.getWindowManager();
12             Display display = windowManager.getDefaultDisplay();
13             
14             int screenWidth = display.getWidth();
15             int screenHeight = display.getHeight();
16             
17             orient = screenWidth < screenHeight? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT :
18                 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
19         }
20         return orient;
21     }
22     
23     public static void AutoBackground(Activity activity, View view, int bg_v, int bg_h) {
24         
25         int orient = ScreenOrient(activity);
26         if (orient == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {//横屏
27             view.setBackgroundResource(bg_h);
28         }
29         else {//竖屏
30             view.setBackgroundResource(bg_v);
31         }
32     }

3. 在MainActivity的onCreate方法中实现

1 LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
2//背景自动适应
3 Utility.AndroidHelper.AutoBackground(this, layout, R.drawable.bg_v, R.drawable.bg_h);

 

posted @ 2014-09-23 19:27  吹小号的程序猿  阅读(802)  评论(0编辑  收藏  举报