android中判断横屏或者竖屏并改变背景

来源:互联网 发布:物理其实很简单. 淘宝 编辑:程序博客网 时间:2024/04/29 16:49

在android中,判断横屏还是竖屏,并且根据方向改变背景,代码如下: 

public static int ScreenOrient(Activity activity)    {        int orient = activity.getRequestedOrientation();         if(orient != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE && orient != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {            //寬>高爲橫屏,反正爲豎屏               WindowManager windowManager = activity.getWindowManager();               Display display = windowManager.getDefaultDisplay();               int screenWidth  = display.getWidth();               int screenHeight = display.getHeight();               orient = screenWidth < screenHeight ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;        }        return orient;    }

public static void AutoBackground(Activity activity,View view,int Background_v, int Background_h)     {         int orient=ScreenOrient(activity);         if (orient == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { //纵向             view.setBackgroundResource(Background_v);         }else{ //横向             view.setBackgroundResource(Background_h);         }      } 



其中Background_v是纵向时的背景图,view.setBackgroundResource为横向时的背景图 

然后在activity的oncreate方法中去调用 
LinearLayout layout=(LinearLayout)findViewById(R.id.layout); 
//背景自动适应 
androidUtil.AutoBackground(this, layout, R.drawable.bg_v, R.drawable.bg_h);
原创粉丝点击