在Android Lollipop上如何声明一个扩展高度的工具栏/操作栏?

88

我在Google Design的应用栏指南中看到了 扩展高度 应用栏。 我如何在Android Lollipop中实现这些效果?

2个回答

145
您需要使用新的工具栏小部件Toolbar实现此目的。 工具栏有特殊处理其最小高度以声明用于按钮(和操作)的空间量。
在下面的示例中,我们将高度设置为128dp(根据规范定义为56dp + 72dp),但保持android:minHeight为标准的actionBarSize(通常为56dp)。这意味着按钮和操作被限制在上面的56dp垂直定位。然后,我们可以使用android:gravity将标题定位在底部。
<Toolbar
    android:id="@+id/toolbar"
    android:layout_height="128dp"
    android:layout_width="match_parent"
    android:minHeight="?android:attr/actionBarSize"
    android:background="?android:attr/colorPrimary"
    android:gravity="bottom" />

如果您使用的是AppCompat,则将声明更改为使用android.support.v7.widget.Toolbar,并使用其属性。


3
如果使用layout_height是正确的方法,那么我期望monsoon在这里描述的解决方法也不再是一个解决方法,而是正确的方法?https://code.google.com/p/android/issues/detail?id=77874 - Thomas Keller
3
我很愿意能够为尺寸声明表达式,但我们无法这样做。 - Chris Banes
37
为了获取额外的积分,请使用增量来调整操作栏的大小,例如@dimen/action_bar_size_x2,在手机上使用112dp,在平板电脑上使用128dp。 - Roman Nurik
7
buttonGravity设置为bottom时,android:paddingBottom属性会导致奇怪的间距问题。在这里,titleMarginBottom属性似乎是更好的选择,对吗? - Paul Burke
5
@RomanNurik 扩展工具栏在日历应用中是如何工作的?有什么提示吗? - Raghunandan
显示剩余9条评论

3
感谢您的问题、答案以及原生和支持库中工具栏的实现 :)
我们可以做更多。在运行时,我们可以玩转高度和最小高度。
高度是工具栏的高度,很简单,每个人都能理解,并且重力根据该高度进行作用。
最小高度更加棘手,不应该小于56dp。这个 minHeight 用于放置您的菜单项的线条。此线条位于最小高度的中心位置。
因此,您可以将此代码添加到您的活动中,以便自己查看差异。 :)
Runnable toolBarAnimator=new Runnable() {
        @Override
        public void run() {
            if(postICS){
//                toolbar.setTranslationX(iteration);
//                toolbar.setElevation(iteration);
                toolbar.setMinimumHeight(iteration * 5);
                toolbar.getLayoutParams().height++;
            }
            uiThreadHanlder.postDelayed(this,16);
            iteration++;
            if(iteration>150)iteration=0;
        }
    };
    Handler uiThreadHanlder=new Handler();
    int iteration=0;


    @Override
    protected void onResume() {
        super.onResume();
        //launch the animation
        uiThreadHanlder.postDelayed(toolBarAnimator, 1000);
    }


    @Override
    protected void onPause() {
        super.onPause();
        //stop the animation
        uiThreadHanlder.removeCallbacks(toolBarAnimator);
    }

工具栏(toolbar)的位置:

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

这样做可以得到如下效果: enter image description here

但是,如果你让动画继续播放,你会得到如下效果: enter image description here

这就是为什么在大多数情况下将工具栏(android:layout_height)设置为wrap_content是一个不错的选择,因为工具栏将根据其内容自适应高度(并且您可以在运行时更改内容 :)

这也是如何在运行时更改工具栏大小的方法。

感谢Chris Banes在操作栏方面所做的出色工作。


@MohammadHadi 我想象中的 postICS 可以这样定义:boolean postICS = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; - dm78

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