Multiple Views Android

Many times,especially in games you may need to have multiple views , a basic OpenglRenderer that occupies the entire surface and you may need to add other views like TextView, AdViews(to promote you apps) , etc on top of it occasionaly. So recently I ran into one such issue for my game wherein I needed to add a view for displaying advertisement banners . So i used Android’s RelativeLayout rather than the default LinearLayout or nested LinearLayouts. So this is the code for 2 views , the main is the Andengine and the other is an advertising banner(Tap for Tap).

So here is the code:

    protected void onSetContentView() {
            final RelativeLayout relativeLayout = new RelativeLayout(this);
            final FrameLayout.LayoutParams relativeLayoutLayoutParams = new FrameLayout.LayoutParams(FILL_PARENT, FILL_PARENT);

            //Create as many views you want
            AdView adView = (AdView) new AdView(this);                                //View1
            adView.layout(0, 0, 50, 100);

            this.mRenderSurfaceView = new RenderSurfaceView(this);                    //View2

            final LayoutParams surfaceViewLayoutParams = new RelativeLayout.LayoutParams(super.createSurfaceViewLayoutParams());
            surfaceViewLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);         //Mention the relative layouts

            relativeLayout.addView(this.mRenderSurfaceView, surfaceViewLayoutParams); //Add the views in order of relative layout
            relativeLayout.addView(adView, this.createAdViewLayoutParams());

            this.setContentView(relativeLayout, relativeLayoutLayoutParams);

    private LayoutParams createAdViewLayoutParams() {
            final LayoutParams adViewLayoutParams = new LayoutParams(400, 50);
            return adViewLayoutParams;

Add this to you Andengine Activity and you are set to go.
To make the view visible or invisible , do .setVisibility(View.VISIBLE) or .setVisibility(View.INVISIBLE).
PS: You need to do the above in the UI thread.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s