我正试图在每次创建活动时获取 "ActionBar "的高度(使用 Sherlock)(特别是在旋转时处理配置更改,因为在旋转时 ActionBar 的高度可能会发生变化)。
为此,我使用了 ActionBar.getHeight()
方法,该方法仅在 ActionBar
显示时有效。
当第一次创建第一个活动时,我可以在 onCreateOptionsMenu
回调中调用 getHeight()
。但之后并没有调用该方法。
所以我的问题是,我什么时候才能调用 getHeight() 并确保它不会返回 0? 如果不可能,我如何设置 ActionBar 的高度?
如果您想明确控制 ActionBar 的大小,@birdy'的答案是一个选择,但我在支持文档中找到了一种方法,可以在不锁定大小的情况下拉出 ActionBar。 虽然有点麻烦,但对我来说还是可行的。 您需要一个上下文,本例在 Activity 中有效。
// Calculate ActionBar height
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
@Anthony 的答案适用于支持 "ActionBar "的设备,而对于只支持 "Sherlock Action Bar "的设备,则必须使用以下方法
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
if(actionBarHeight ==0 && getTheme().resolveAttribute(com.actionbarsherlock.R.attr.actionBarSize, tv, true)){
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
//OR as stated by @Marina.Eariel
TypedValue tv = new TypedValue();
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}else if(getTheme().resolveAttribute(com.actionbarsherlock.R.attr.actionBarSize, tv, true){
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
要设置 "ActionBar "的高度,可以像这样创建新的 "主题":
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.FixedSize" parent="Theme.Sherlock.Light.DarkActionBar">
<item name="actionBarSize">48dip</item>
<item name="android:actionBarSize">48dip</item>
</style>
</resources>
并将此 "主题 "设置为您的 "活动":
android:theme="@style/Theme.FixedSize"