封装类方法(AndroidHelper类):
//获取屏幕方向
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);
}
}
xml文件(布局文件):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>
代码实现(OnCreate方法):
//获取xml文件中的layout
LinearLayout layout=(LinearLayout)findViewById(R.id.layout);
//背景自动适应
AndroidHelper.AutoBackground(this, layout, R.drawable.bg_v, R.drawable.bg_h);
浙公网安备 33010602011771号