在ActionBar上方添加一行/图像

时间:2014-02-04 12:46:13

标签: java android android-actionbar

我想在操作栏上方添加一行,就像在“pocket”-app中一样。我怎么能这样做?

这是一张图片,例如: pocket_example

由于 TomTom的

1 个答案:

答案 0 :(得分:1)

利用Activity的WindowManager,我们可以在顶部绘制我们想要的任何视图。这是一些应该有用的(半伪)代码:

// Create an instance of some View that does the actual drawing of the line
View customView = new CustomView(<some context>);

// Figure out the window we have to work with
Rect rect = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);

// Make sure the view is measured before doing this
int requestedHeight = customView.getLayoutParams().height;

// setup the params of the new view we'll attach
WindowManager.LayoutParams wlp = new WindowManager.LayoutParams(
     rect.width(), requestedHeight,
     WindowManager.LayoutParams.TYPE_APPLICATION_PANEL,
     WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | 
          WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
          WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
     PixelFormat.TRANSLUCENT);
// set the parameters so we fit on the top left of the window
wlp.x = 0;
wlp.y = rect.top;
wlp.gravity = Gravity.TOP;

// finally add it to the screen
getWindowManager().addView(header, wlp);

唯一需要注意的是,您无法从onCreate()或Activity的任何生命周期方法运行该代码,因为尚未创建Window(您将获得BadTokenException)。一种方法可能是在Window的DecorView上发布Runnable,以便在创建Window之后运行添加CustomView的代码:

 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     //...
     getWindow().getDecorView().post(<Runnable that execs code above>);
 }

对于将显示多色条的实际 CustomView ,我觉得这是一个很好的练习:-) 您需要做的就是让onDraw()方法使用具有特定x和宽度的canvas.drawRect()。

希望有所帮助。

Pocket做什么

至于Pocket实际上是如何做到的。如果您在Pocket应用程序上使用HierarchyViewer,您将能够确定Pocket为其ActionBar使用自定义类。由于他们已经根据需要重建了ActionBar的所有功能,因此在他们的情况下,添加该行就像将常规视图添加到某个ViewGroup。

相关问题