如何灵活使用 ActionBar, Google 音乐ActionBar 隐藏和显示效果

ActionBar 的历史这里就不介绍了,,相信大家都清楚;在一个 app 中,如果 ActionBar 运用的好,那么将会省去大量的代码,而且整个 app 效果也相当不错,大家有兴趣可以下载 google music 这款 app 看看,界面看起来还是相当舒服的; ok,这里教大家一招快捷方便使用 ActionBar 的方法。

还记得我写过的一篇 blog Android AlertDialog对话框自定义风格的另类实现,没错,这里就是要使用那篇 blog 中讲到的这个方法。

(String name, String defType, String defPackage) {if (name == null) {throw new NullPointerException(“name is null”);}try {return Integer.parseInt(name);} catch (Exception e) {// Ignore}return mAssets.getResourceIdentifier(name, defType, defPackage);}

看到这个大家不会觉得陌生了吧! 不过这个方法需要知道 ActionBar 控件的 id 名称,这里我就直接告诉大家是 ” action_bar_container”

<androidandroid:id=”@+id/action_bar_container”android:layout_width=”match_parent”android:layout_height=”wrap_content”android:layout_alignParentTop=”true”style=”?attr/actionBarStyle”android:touchscreenBlocksFocus=”true”android:gravity=”top”><androidandroid:id=”@+id/action_bar”android:layout_width=”match_parent”android:layout_height=”wrap_content”app:navigationContentDescription=”@string/abc_action_bar_up_description”style=”?attr/toolbarStyle”/>

还是很容易找到的。 所以,我们就能很轻易的拿到 ActionBar 的 View 具体代码如下:

private View getActionBarView(){View view = getWindow().getDecorView() ;int actionBarId = getResources().getIdentifier(“action_bar_container”,”id”,getPackageName()) ;return view.findViewById(actionBarId) ;}

拿到了 View 之后我们能干嘛?来看两张图:

ActionBar 颜色改变了,并且沿着 X轴旋转了一定角度

这。。。纵向 ActionBar,第一次见吧!

通过以上两副图,只是想说明一点,拿到了 ActionBar 的 View,我们就能灵活的控制 ActionBar,比如 Google Music 的显示和隐藏效果,下面就来看看怎么实现的。

先看动态图:

这个效果是,当 RecyclerView 向上滑动 ActionBar 显示,向下滑动 ActionBar 隐藏,并且是随着滑动的距离来控制ActionBar 的移动距离。 代码非常之简单

(RecyclerView recyclerView, int dx, int dy) {super.onScrolled(recyclerView, dx, dy);int transY = (int) (mActionBarView.getTranslationY() – dy);//控制 ActionBar 的移动距离不能超过边界transY = (int) clamp(transY,-mActionBarHeight,0);mActionBarView.setTranslationY(transY);}

但松手之后,还有一个动画需要处理,如果 ActionBar 的显示高度大于 ActionBar 高度的一半,则让它做全部显示动画,反之,则做隐藏动画。

(RecyclerView recyclerView, int newState) {super.onScrollStateChanged(recyclerView, newState);if (newState == RecyclerView.SCROLL_STATE_IDLE){checkAnimation() ;}}(){int transY = (int)mActionBarView.getTranslationY();if (transY != 0|| transY != -mActionBarHeight){startAnimation() ; }}(){float [] value = new float[2] ;value[0] = mActionBarView.getTranslationY();if (value[0] > -mActionBarHeight/2.0f){value[1] = 0 ;}else {value[1] = – mActionBarHeight ;}ObjectAnimator animator =ObjectAnimator.ofFloat(MainActivity.this,”transY”,value) ; animator.setDuration(150) ; animator.start();}

这里主要是一些动画和平移的处理,如果不熟悉可以把源码下载下来分析。

总结:

ActionBar 的 View获取主要还是借助以下这个方法来获取

public int getIdentifier(String name, String defType, String defPackage)

需要对AcitonBar 的资源 id 的名称了解,这个可以通过查看源码知道。

源码下载地址:我是代码

让你的心情地落到极点,一直学习生活等各个方面都做不好,最终害的还是自己。

如何灵活使用 ActionBar, Google 音乐ActionBar 隐藏和显示效果

相关文章:

你感兴趣的文章:

标签云: