Android修改全局Window窗口大小

在项目开发过程中,如果屏幕宽高比过于悬殊,例如电视大小的安卓设备(定制),在显示应用的时候需要居中显示,两边留白,按照手机大小显示应用。怎么实现呢?
思路是通过修改应用的window大小来实现。但是window是绑定activity的,所以需要修改所有界面的window大小。

实现效果如下:

实现方式如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 定义activity生命周期监听
private ActivityLifecycleCallbacks mActivityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (Build.MODEL.equalsIgnoreCase("3280")
&& Build.MANUFACTURER.equalsIgnoreCase("rockchip")) {
//特殊设备,设置宽度
WindowManager m = activity.getWindowManager();
Display d = m.getDefaultDisplay(); //为获取屏幕宽、高
android.view.WindowManager.LayoutParams p = activity.getWindow().getAttributes(); //获取对话框当前的参数值
p.height = (int) (d.getHeight() * 1); //高度设置为屏幕的0.6
p.width = (int) (d.getWidth() * 0.50); //宽度设置为屏幕的0.95
activity.getWindow().setAttributes(p); //设置生效
}
}

@Override
public void onActivityStarted(Activity activity) {

}

@Override
public void onActivityResumed(Activity activity) {

}

@Override
public void onActivityPaused(Activity activity) {

}

@Override
public void onActivityStopped(Activity activity) {

}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

}

@Override
public void onActivityDestroyed(Activity activity) {

}
};

在application中注册

1
2
3
4
5
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks);
}

application注销的时候取消注册

1
2
3
4
5
@Override
public void onTerminate() {
super.onTerminate();
unregisterActivityLifecycleCallbacks(mActivityLifecycleCallbacks);
}

分享到