为什么像下面这样获得有效的屏幕尺寸(screen-actionbar-statusbar)会在不同的时间给出不同的结果?我的 fragment 第一次启动并调用 getEffectiveScreenSize 时出错(操作栏大小为 0),但第二次和其余时间都是正确的。
所以像下面这样获取 actionbar 大小是不可靠的,为什么?正确安全的方法是什么?
public static Point getScreenSize( Activity theActivity )
{
Display theDisplay = theActivity.getWindowManager().getDefaultDisplay();
Point sizePoint = new Point();
theDisplay.getSize( sizePoint );
return sizePoint;
}
public static int getStatusBarHeight( Activity theActivity )
{
int result = 0;
int resourceId = theActivity.getResources().getIdentifier( "status_bar_height", "dimen", "android" );
if (resourceId > 0)
{
result = theActivity.getResources().getDimensionPixelSize( resourceId );
}
return result;
}
public static int getActionBarHeight( Activity theActivity )
{
return theActivity.getActionBar().getHeight();
}
public static Point getEffectiveScreenSize( Activity theActivity )
{
Point screenSize = getScreenSize( theActivity );
screenSize.y = screenSize.y - getStatusBarHeight( theActivity ) - getActionBarHeight( theActivity );
return screenSize;
}
此更改没有帮助:
public static int getActionBarHeight( Activity theActivity )
{
//return theActivity.getActionBar().getHeight();
int result = 0;
int resourceId = theActivity.getResources().getIdentifier( "actionbar_bar_height", "dimen", "android" );
if (resourceId > 0)
{
result = theActivity.getResources().getDimensionPixelSize( resourceId );
}
return result;
}
最佳答案
我不确定为什么您的所有方法都是静态的,但更重要的是,由于某种原因您没有包含相关代码 - getEffectiveScreenSize
在哪里使用?
我能给你的最佳答案必须基于假设 - 你必须在 lifecycle 的不同点调用 getEffectiveScreenSize
- 在测量布局之前和之后和/或操作栏完全初始化之前(可能查看 callbacks related to action bar )。
如果你想让你的布局考虑到操作栏,你可以使用一个维度
?android:attr/actionBarSize
如果您试图制作或停止内容和操作栏重叠,那么您可能必须更改样式中操作栏叠加的值
<item name="android:windowActionBarOverlay">bool</item>
关于Android - 获取操作栏大小会产生不一致的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22082792/