代码之家  ›  专栏  ›  技术社区  ›  znat

如何获取ActionBar的高度?

  •  215
  • znat  · 技术社区  · 12 年前

    我正在努力达到 ActionBar (使用Sherlock)每次创建活动时(特别是为了处理ActionBar高度可能更改的旋转配置更改)。

    为此,我使用了 ActionBar.getHeight() 只有当 操作栏 如图所示。

    当第一次创建第一个活动时,我可以调用 getHeight() onCreateOptionsMenu 回调。但此方法不会在之后调用。

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

    21 回复  |  直到 12 年前
        1
  •  454
  •   ingh.am    3 年前

    如果你想明确控制ActionBar的大小,@birdy的答案是一个选项,但有一种方法可以在不锁定我在支持文档中找到的大小的情况下将其拉上来。这有点尴尬,但对我来说很有效。你需要一个上下文,这个例子在活动中是有效的。

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

    科特林 以下为:

    val tv = TypedValue()
    if (requireActivity().theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
        val actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, resources.displayMetrics)
    }
    
        2
  •  158
  •   Aerilys    10 年前

    在XML中,应该使用以下属性:

    android:paddingTop="?android:attr/actionBarSize"
    
        3
  •  18
  •   hris.to    11 年前

    好吧,我在谷歌上搜索了好几次,所以我认为这将是一个很好的描述,不仅是夏洛克,还有appcompat:

    使用appCompat的操作栏高度

    与@Anthony的描述非常相似,您可以通过以下代码找到它(我刚刚更改了资源id):

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

    Sandwitch之前的问题

    我需要动作条的高度,因为在ICE_CREAM_SANDWICH之前的设备上,我的视图覆盖了动作条。我试着设置android:layout_marginTop=“?android:attr/actionBarSize”,android:layout_marginTop=“?attr/actionBarSize”,设置重叠以查看/actionbar,甚至使用自定义主题固定actionbar高度,但都没用。这就是它的样子:

    overlap problem

    不幸的是,我发现用上面描述的方法我只得到了一半的高度(我假设选项栏没有就位),所以为了完全修复isue,我需要 双重的 动作条高度和一切似乎都很好:

    overlap fixed

    如果有人知道更好的解决方案(比加倍actionBarHeight),我很高兴告诉我,因为我来自iOS开发,我发现Android视图的大部分内容都很令人困惑:)

    当做

    hris.to公司

        4
  •  16
  •   laaptu    11 年前

    @Anthony answer适用于支持 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());
       }
    
        5
  •  14
  •   android developer    11 年前

    我认为最安全的方法是:

    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;
    }
    
        6
  •  7
  •   znat    12 年前

    设置的高度 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>
    

    并设置 主题 到您的 Activity 以下为:

    android:theme="@style/Theme.FixedSize"
    
        7
  •  6
  •   jk7    7 年前

    如果使用Toolbar作为ActionBar,

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

    然后只使用工具栏的layoutheight。

    int actionBarHeight = toolbar.getLayoutParams().height;
    
        8
  •  5
  •   TeeTracker    10 年前

    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
    
        9
  •  3
  •   Fred    9 年前

    如果您正在使用Xamarin/C#,以下是您要查找的代码:

    var styledAttributes = Context.Theme.ObtainStyledAttributes(new[] { Android.Resource.Attribute.ActionBarSize });
    var actionBarSize = (int)styledAttributes.GetDimension(0, 0);
    styledAttributes.Recycle();
    
        10
  •  3
  •   wangzhengyi    9 年前

    您可以使用此函数来获取actionbar的高度。

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

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

    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;
    }
    
        12
  •  3
  •   bboyairwreck    5 年前

    以下是我使用的Kotlin的更新版本,假设手机高于Honeycomb:

    val actionBarHeight = with(TypedValue().also {context.theme.resolveAttribute(android.R.attr.actionBarSize, it, true)}) {
                TypedValue.complexToDimensionPixelSize(this.data, resources.displayMetrics)
            }
    
        13
  •  2
  •   Simon    10 年前

    这种辅助方法应该会派上用场。示例: 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();
            }
        }
    }
    
        14
  •  2
  •   JCDecary    10 年前

    你只需要加上这个。

    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;
        }
    
        15
  •  2
  •   Alécio Carvalho Kingfisher Phuoc    9 年前

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

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

    其中' 主视图 '是布局的根视图。

    这个想法基本上是得到 主视图 因为它设置在ActionBar(或Toolbar)的正下方。

        16
  •  2
  •   Mahmoud    8 年前

    动作栏的高度因应用的主题而异。 如果您正在使用 应用程序兼容性活动 在大多数情况下,高度将与正常活动不同。

    如果您正在使用 应用程序兼容性活动 应该使用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));
        }
    
        17
  •  2
  •   Fakhriddin Abdullaev    6 年前

    在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;
        }
    
        18
  •  1
  •   Devraj Singh    8 年前
    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();
    }
    
        19
  •  0
  •   Harshad Pansuriya    8 年前

    找到操作条高度的一个简单方法是从“活动” onPrepareOptionMenu 方法

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
               ....
               int actionBarHeight = getActionBar().getHeight());
               .....
        }
    
        20
  •  0
  •   Lealo    7 年前

    在javafx(使用Gloon)中,高度是在运行时或类似的时候设置的。。。

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

    …并取它更改为的最新值。获取高度。

        21
  •  0
  •   Rafael Pereira    7 年前

    在尝试了所有没有成功的东西之后,我意外地发现了一种功能强大且非常简单的方法来获得动作条的默认高度。

    仅在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);