在XML中设置Android导航栏大小

27

有没有类似于这样在android的xml文件中获取导航栏大小的方法?

 android:paddingTop="?android:attr/actionBarSize"

actionBarSize是导航栏的尺寸吗?


你是指“ActionBar”而不是“导航栏”吗?如果你需要获取“ActionBar”的高度,请参考这个问题:https://dev59.com/OWct5IYBdhLWcg3wKqUd - Droidman
4
不,我的意思是导航栏(在没有硬件按钮的设备上显示的那个)。 - fragon
3个回答

35

在查看Android源代码后,似乎有导航栏高度的尺寸:

@android:dimen/navigation_bar_height

这里还有与导航栏相关的其他尺寸,例如来自Android values/dimens.xml的示例:

<!-- Height of the bottom navigation / system bar. -->
<dimen name="navigation_bar_height">48dp</dimen>
<!-- Height of the bottom navigation bar in portrait; often the same as @dimen/navigation_bar_height -->
<dimen name="navigation_bar_height_landscape">48dp</dimen>
<!-- Width of the navigation bar when it is placed vertically on the screen -->
<dimen name="navigation_bar_width">42dp</dimen>

48
错误:(167,39)资源不是公共的。(在“layout_marginBottom”中,值为“@android:dimen/navigation_bar_height”)。 - Ion Aalbers
@IonAalbers 你正在使用哪个版本的Android? - Gaëtan Maisse
同样的问题。有解决方案吗? - Prior99
1
我遇到了与Ion Aalbers相同的问题。使用Max的解决方案对我有用,所以我将我的填充和边距移动到onCreate中。 - Tilded
AAPT错误:资源android:dimen/navigation_bar_height是私有的。 - Ali Hassan
显示剩余3条评论

8

试试这个代码

Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
    return resources.getDimensionPixelSize(resourceId);
}
return 0;

2
OP特别要求使用XML。 - Allan Veloso

2

正如类似问题thisthisthisthis中建议的那样,仅获取导航栏高度可能不足够。我们需要考虑以下几点:1. 导航栏是否存在,2. 是否在底部、右侧或左侧,3. 应用程序是否在多窗口模式下打开。

有一个简单的一行解决方案。

android:fitsSystemWindows="true"

或者通过编程方式
findViewById(R.id.your_root_view).setFitsSystemWindows(true);

您可以通过以下方式获取根视图:

findViewById(android.R.id.content).getRootView();
or
getWindow().getDecorView().findViewById(android.R.id.content)

获取根视图的更多详细信息,请参考- https://dev59.com/Ym855IYBdhLWcg3wMBPV#4488149


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接