tom_tom
tom_tom

Reputation: 465

Add a Line/Image above ActionBar

I want to add a line above the action bar like in the "pocket"-app. How can i do this?

Here is a picture for example: pocket_example

Thanks tomtom

Upvotes: 1

Views: 245

Answers (1)

kwazi
kwazi

Reputation: 592

Taking advantage of an Activity's WindowManager, we can draw any view we want on top. Here's some (half-pseudo) code that should help:

// 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);

The only thing to be careful is that you can't run that code from onCreate() or any lifecycle method of the Activity because the Window won't have been created yet (You'll get a BadTokenException). One way might be post a Runnable on the Window's DecorView so that your code to add the CustomView runs after the Window is created:

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

As for the actual CustomView that will display that multi-coloured bar, I feel like that's a good exercise :-) All you'd need to do is have the onDraw() method use canvas.drawRect() with specific x and widths.

Hope that helps.

What Pocket does

As for how Pocket actually does it. If you use HierarchyViewer on the Pocket app, you'll be able to determine that Pocket uses a custom class for their ActionBar. Since they already rebuild all the features of the ActionBar for their needs, in their case, adding the line is like adding a regular View to some ViewGroup.

Upvotes: 1

Related Questions