首页 文章

如何获得ActionBar高度?

提问于
浏览
162

我每次创建一个活动时都试图获得 ActionBar (使用Sherlock)的高度(特别是为了处理ActionBar高度可能改变的旋转配置更改) .

为此,我使用方法 ActionBar.getHeight() ,该方法仅在显示 ActionBar 时有效 .

当第一次创建第一个活动时,我可以在 onCreateOptionsMenu 回调中调用 getHeight() . 但是这个方法之后没有被调用 .

所以我的问题是我什么时候可以调用getHeight()并确保它不会返回0?或者如果不可能,我如何设置ActionBar的高度?

20 回答

  • 1

    虽然@ 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());
    }
    
  • 2

    在XML中,您应该使用此属性:

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

    好吧,我正在谷歌上搜索并多次访问这个帖子,所以我认为不仅对Sherlock而且对appcompat也有好处:

    Action Bar height using appCompat

    与@Anthony描述相似,您可以使用以下代码找到它(我刚刚更改了资源ID):

    TypedValue tv = new TypedValue();
    
    if (getActivity().getTheme().resolveAttribute(R.attr.actionBarSize, tv, true))
    {
        int actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
    }
    

    Pre Sandwitch Problem

    我需要操作栏高度,因为在ICE_CREAM_SANDWITCH设备之前,我的视图是重叠操作栏 . 我尝试设置android:layout_marginTop =“?android:attr / actionBarSize”,android:layout_marginTop =“?attr / actionBarSize”,将重叠设置为视图/操作栏,甚至修改了自定义主题的动作栏高度,但没有任何效果 . 这就是它的样子:

    overlap problem

    不幸的是我发现用上面描述的方法我得到的高度只有一半(我假设选项栏没有采取到位)所以要完全修复我需要 double 动作条高度,一切似乎都可以:

    overlap fixed

    如果有人知道更好的解决方案(而不是加倍actionBarHeight)我会很高兴让我知道,因为我来自iOS开发,我发现大多数Android视图的东西很混乱:)

    问候,

    hris.to

  • 137

    @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());
       }
    
  • 4

    我认为最安全的方式是:

    private int getActionBarHeight() {
        int actionBarHeight = getSupportActionBar().getHeight();
        if (actionBarHeight != 0)
            return actionBarHeight;
        final 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());
        return actionBarHeight;
    }
    
  • 2

    要设置 ActionBar 的高度,您可以像这样创建新的 Theme

    <?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>
    

    并将此 Theme 设置为 Activity

    android:theme="@style/Theme.FixedSize"
    
  • 3

    Java的:

    int actionBarHeight;
        int[] abSzAttr;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            abSzAttr = new int[] { android.R.attr.actionBarSize };
        } else {
            abSzAttr = new int[] { R.attr.actionBarSize };
        }
        TypedArray a = obtainStyledAttributes(abSzAttr);
        actionBarHeight = a.getDimensionPixelSize(0, -1);
    

    XML:

    ?attr/actionBarSize
    
  • 1

    如果您使用工具栏作为ActionBar,

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    

    然后只需使用工具栏的layout_height .

    int actionBarHeight = toolbar.getLayoutParams().height;
    
  • 2

    你可以使用这个功能来获得动作栏的高度 .

    public int getActionBarHeight() {
        final TypedArray ta = getContext().getTheme().obtainStyledAttributes(
                new int[] {android.R.attr.actionBarSize});
        int actionBarHeight = (int) ta.getDimension(0, 0);
        return actionBarHeight;
    }
    
  • 4

    这个辅助方法对某人来说应该派上用场 . 示例: int actionBarSize = getThemeAttributeDimensionSize(this, android.R.attr.actionBarSize);

    public static int getThemeAttributeDimensionSize(Context context, int attr)
    {
        TypedArray a = null;
        try{
            a = context.getTheme().obtainStyledAttributes(new int[] { attr });
            return a.getDimensionPixelSize(0, 0);
        }finally{
            if(a != null){
                a.recycle();
            }
        }
    }
    
  • 1

    你只需添加这个 .

    public int getActionBarHeight() {
            int height;
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                height = getActivity().getActionBar().getHeight();
            } else {
                height = ((ActionBarActivity) getActivity()).getSupportActionBar().getHeight();
    
            }
            return height;
        }
    
  • 0

    我发现了一种更通用的方法来发现它:

    int[] location = new int[2];
      mainView.getLocationOnScreen(location);
      int toolbarHeight = location[1];
    

    其中' mainView '是布局的根视图 .

    这个想法基本上是 mainView 的Y位置,因为它位于ActionBar(或工具栏)的正下方 .

  • 372

    操作栏高度根据应用的主题而不同 . 如果你正在使用 AppCompatActivity ,那么在大多数情况下,身高与普通活动的高度会有所不同 .

    如果您正在使用 AppCompatActivity ,则应使用R.attr.actionBarSize而不是android.R.attr.actionBarSize

    public static int getActionBarHeight(Activity activity) {
            TypedValue typedValue = new TypedValue();
    
            int attributeResourceId = android.R.attr.actionBarSize;
            if (activity instanceof AppCompatActivity) {
                attributeResourceId = R.attr.actionBarSize;
            }
    
            if (activity.getTheme().resolveAttribute(attributeResourceId, typedValue, true)) {
                return TypedValue.complexToDimensionPixelSize(typedValue.data, activity.getResources().getDisplayMetrics());
            }
    
            return (int) Math.floor(activity.getResources()
                    .getDimension(R.dimen.my_default_value));
        }
    
  • 2

    在xml中,您可以使用?attr / actionBarSize,但如果您需要在Java中访问该值,则需要使用以下代码:

    public int getActionBarHeight() {
            int actionBarHeight = 0;
            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 {
                actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,
                        getResources().getDisplayMetrics());
            }
            return actionBarHeight;
        }
    
  • 2

    如果你正在使用Xamarin / C#,这是你正在寻找的代码:

    var styledAttributes = Context.Theme.ObtainStyledAttributes(new[] { Android.Resource.Attribute.ActionBarSize });
    var actionBarSize = (int)styledAttributes.GetDimension(0, 0);
    styledAttributes.Recycle();
    
  • 15
    The action bar now enhanced to app bar.So you have to add conditional check for getting height of action bar.
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
       height = getActivity().getActionBar().getHeight();
     } else {
      height = ((ActionBarActivity) getActivity()).getSupportActionBar().getHeight();
    }
    
  • 0

    一种现成的方法来实现最流行的答案:

    public static int getActionBarHeight(
      Activity activity) {
    
      int actionBarHeight = 0;
      TypedValue typedValue = new TypedValue();
    
      try {
    
        if (activity
          .getTheme()
          .resolveAttribute(
            android.R.attr.actionBarSize,
            typedValue,
            true)) {
    
          actionBarHeight =
            TypedValue.complexToDimensionPixelSize(
              typedValue.data,
              activity
                .getResources()
                .getDisplayMetrics());
        }
    
      } catch (Exception ignore) {
      }
    
      return actionBarHeight;
    }
    
  • 0

    查找操作栏高度的简单方法来自Activity onPrepareOptionMenu 方法 .

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
               ....
               int actionBarHeight = getActionBar().getHeight());
               .....
        }
    
  • 12

    在javafx(使用Gluon)中,高度是在运行时或类似的东西设置的 . 虽然能够像正常一样获得宽度......

    double width = appBar.getWidth();

    你必须创建一个监听器:

    GluonApplication application = this;

    application.getAppBar().heightProperty().addListener(new ChangeListener(){
        @Override
        public void changed(ObservableValue observable, Object oldValue, Object newValue) {
            // Take most recent value given here
            application.getAppBar.heightProperty.get()
        }
    });
    

    ......并将其最新 Value 改为 . 获得高度 .

  • 6

    在尝试了那些没有成功的东西之后,我偶然发现了一个功能性且非常简单的方法来获得操作栏的默认高度 .

    仅在API 25和24中测试过

    C#

    Resources.GetDimensionPixelSize(Resource.Dimension.abc_action_bar_default_height_material);
    

    Java的

    getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);
    

相关问题