Pages

getteammates.com

Saturday, 4 November 2017

Native Android UI with Unity 5.6

In Unity 5.6 the surface view object that it uses to render its graphics element is set as on top of all other views.
Due to this if you are going to add Android Views using addContentView it will not be getting displayed. For some reason it gets clickable events, so your callback will be fired.

Google ads uses PopupWindow to overcome this issue(a transparent PopupWindow with views added into it), you can see their implementation at https://github.com/googleads/googleads-mobile-unity/tree/master/source/android-library/app/src/main/java/com/google/unity/ads

It will work for you as well if your views only covers part of the window and you need not pass the click event through the PopupWindow.
Suppose you have views at the top and bottom of the window and you create a full screen PopupWindow then Unity's SurfaceView will not receive click events.

Another appraoch, maybe a little dirty, is to find the SurfaceView in the view hierarchy, remove it, set
setZOrderOnTop(false) and add it back. See the code block below,
/**
 * @param view This is the view that you want to add on top of Unity's SurfaceView
 * @param activity Unity applications Activity
 */
void addUIView(View view, Activity activity) {
        ViewGroup viewGroup = (ViewGroup)activity.findViewById(android.R.id.content);
        SurfaceView surfaceView = getSurfaceView(viewGroup);
        if (surfaceView != null) {
            ((ViewGroup)surfaceView.getParent()).removeView(surfaceView);
        }
        surfaceView.setZOrderOnTop(false);  // This should help us in getting our view displayed
        activity.setContentView(surfaceView);
        activity.addContentView(view, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT));
}
/**
 * Get SurfaceView object by traversing the View heirarchy
 */
private SurfaceView getSurfaceView(ViewGroup parentView) {
        int numChildViews = parentView.getChildCount();
        for (int i = 0; i < numChildViews; i++) {
            View childView = parentView.getChildAt(i);
            if (childView instanceof ViewGroup) {
                SurfaceView surfaceView = getSurfaceView((ViewGroup)childView);
                if (surfaceView != null) {
                    return surfaceView;
                }
            }
            else if (childView instanceof SurfaceView) {
                return (SurfaceView)childView;
            }
        }
        return null;
}