android中判斷橫屏或者豎屏並改變背景

在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);
發佈了238 篇原創文章 · 獲贊 25 · 訪問量 109萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章