gustavaa gustavaa - 8 days ago 7
Android Question

How can I draw a View on top of it´s parent-layout?

So I'm writing a custom component which basically is an EditText with a custom drop-down menu attached at the bottom. This will host a list of search suggestions. Right now I accomplish this by extending a LinearLayout with an EditText and my SuggestionBox-View inside. I.e I use

this.addView(searchEditText);

and
this.addView(suggestionBox);


This works fine, but when I put the component inside a LinearLayout, the views underneath my component are moved to make room for the drop-down menu.

I want the dropdown to overlay any other views in the containing layout. How can I do this?

For an example, if the component is used in a LinearLayout with views underneath it, I want the drop-down list to overlay the other views.

Now, I know this can be accomplished by using a FrameLayout as parent layout, but I want the component to be usable regardless of what parent layout is being used.

Answer

Okay so I should probably post an answer to this problem in case someone stumbles upon this question. I managed to solve it with a bit of an ugly fix. I find the main content view with the line below and then add my custom view directly to it.

FrameLayout layout = (FrameLayout) ((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content);

Then in OnLayoutChange() I send it to the top of the layout stack.

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
    listParams.setMargins(getLeft(),getTop()+getHeight(),getRight(),getBottom());
    list.setLayoutParams(listParams);
    list.bringToFront();
}

There is however another way (probably much better) to do it. And that is by using the class PopupWindow class. I haven't tried this out fully yet but it should be used something like this:

PopupWindow window = new PopupWindow();
    window.setContentView(customView);

And then add this to the view.

Hope this helps someone!