Reputation: 18729
I would like to be able to display any Fragment as overlay above any Activity. The result should look something like this:
The easiest way to achieve this would be to place an additional FrameLayout within the activity which is invisible. When the overlay should be shown it can be placed within the FrameLayout which is then set to be visible.
This works fine but of course only in Activities that are prepared to do so. Additionally this will not overlay the action bar. I am looking for a more generic approach. Something like this:
// In Activity
public void showFragmentOverlay() {
SomeFragment someFragment = new SomeFragment();
FragmentOverlay overlay = new FragmentOverlay(this, someFragment);
overlay.show();
}
// Overlay class
public class FragmentOverlay {
private Activity activity;
private Fragment fragment;
public FragmentOverlay(Activity activity, Fragment fragment) {
this.activity = activity;
this.fragment = fragment;
}
private FrameLayout frameLayout;
public void show() {
// Find root view/layout somehow
// Create FrameLayout programmatically and place it in the root layout
// Add Fragment to FrameLayout
}
public void close() {
// Remove FrameLayout from root layout
}
}
I am using a quite similar solution on iOS by simply adding a view directly to the window to overlay all other views. However I was not able to get this running on Android. Problem is, that I did not found out how find/get a Root-Layout. Finding the Root view was no problem (activity.getWindow().getDecorView().getRootView()) but I need a ViewGroup/Layout to be able to add a new child.
How can this be done on Android?
Upvotes: 4
Views: 1767
Reputation: 15973
You can try the following:
View mTopView = getLayoutInflater().inflate(R.layout.activity2, null);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
getResources().getDisplayMetrics().widthPixels,
getResources().getDisplayMetrics().heightPixels,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
PixelFormat.TRANSLUCENT);
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(mTopView, params);
You need to add this permission in the manifest:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
Upvotes: 1