我需要知道动作栏的像素大小,以便应用正确的背景图像。
当前回答
Kotlin接受答案:
val Context.actionBarSize
get() = theme.obtainStyledAttributes(intArrayOf(android.R.attr.actionBarSize))
.let { attrs -> attrs.getDimension(0, 0F).toInt().also { attrs.recycle() } }
用法:
val size = actionBarSize // Inside Activity
val size = requireContext().actionBarSize // Inside Fragment
val size = anyView.context.actionBarSize // Inside RecyclerView ViewHolder
其他回答
我这样做是为了自己,这个帮手方法应该对其他人有用:
private static final int[] RES_IDS_ACTION_BAR_SIZE = {R.attr.actionBarSize};
/**
* Calculates the Action Bar height in pixels.
*/
public static int calculateActionBarSize(Context context) {
if (context == null) {
return 0;
}
Resources.Theme curTheme = context.getTheme();
if (curTheme == null) {
return 0;
}
TypedArray att = curTheme.obtainStyledAttributes(RES_IDS_ACTION_BAR_SIZE);
if (att == null) {
return 0;
}
float size = att.getDimension(0, 0);
att.recycle();
return (int) size;
}
@AZ13的回答很好,但根据Android设计指南,动作栏至少应该是48dp高。
课程摘要通常是一个很好的开始。我认为getHeight()方法就足够了。
编辑:
如果你需要宽度,它应该是屏幕的宽度(对吧?),可以像这样收集。
要在XML中检索ActionBar的高度,只需使用
?android:attr/actionBarSize
或者如果你是ActionBarSherlock或AppCompat用户,使用这个
?attr/actionBarSize
如果在运行时需要此值,请使用此值
final TypedArray styledAttributes = getContext().getTheme().obtainStyledAttributes(
new int[] { android.R.attr.actionBarSize });
mActionBarSize = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
如果你需要了解它的定义:
属性名本身定义在平台的/res/values/attrs.xml文件中 平台的themes.xml选择此属性并为其赋值。 在第2步中分配的值取决于不同的设备大小,这些设备大小在平台中的各种dimensions .xml文件中定义,例如。核心/ res / res / values-sw600dp / dimens.xml
为了获得动作栏的实际高度,你必须在运行时解析actionBarSize属性。
TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
int actionBarHeight = getResources().getDimensionPixelSize(tv.resourceId);
推荐文章
- 从资产中读取文件
- 在不活动的地方调用getLayoutInflater()
- 设置Android布局元素的背景颜色
- 错误:'keytool'不能被识别为内部或外部命令、可操作程序或批处理文件
- 在应用程序本身中更改Locale
- apk (.apk)和应用程序包(.aab)的区别
- 如何设置超时在改造库?
- Android - SPAN_EXCLUSIVE_EXCLUSIVE跨度不能为零长度
- TextView的字体大小在Android应用程序改变字体大小从本机设置
- 如何模拟Android杀死我的进程
- 禁用EditText闪烁光标
- Android Eclipse -无法找到*.apk
- 设置TextView文本从html格式的字符串资源在XML
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- Android加载JS包失败