Android - 获取操作栏大小会产生不一致的结果

标签 android android-actionbar android-screen

为什么像下面这样获得有效的屏幕尺寸(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/

相关文章:

android - 当具有测试帐户的 Alpha 应用程序时,开发人员有效负载是否有效?

java - 监听 ListView 中按钮的点击

Honeycomb 的 Android ActionBar 选项卡样式

android - 如何使用 Holo.Light 主题但让 ActionBar 使用没有 ICS 的 Hulu?

android - 如何为多个屏幕分辨率定义可绘制文件夹名称(Nexus 10 和 Galaxy Tab 10 之间的冲突)?

Android:未正确报告屏幕密度

java - 我的表没有在 Sqlite 中创建(Toast for dataNotInserted)....下面的代码 fragment

Android - ActionBarSherlock - 设置子菜单中文本的文本颜色

Android 资源 notlong/long 标识符不起作用

java - 移动不适合手指的 View