2

I want to add a View at the bottom of an existing layout, regardless of the type of ViewGroup (Linear, Relative etc...) which is defined in the Activity layout file

The Activity layout file looks like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get Ad"
    android:layout_centerInParent="true"
    android:onClick="showAdd"/>
 </RelativeLayout>

and this is the code for placing the View:

ViewGroup rootView = (ViewGroup)((Activity) m_context).findViewById(android.R.id.content);
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT);
    lay.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    rootView.addView(adView,lay);

The problem is that the View appears in the middle of the screen and not at the bottom, as expected

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Michael A
  • 5,770
  • 16
  • 75
  • 127
  • why you put match_parent for button? try wrap_content – LunaVulpo Oct 25 '16 at 10:48
  • @LunaVulpo I tried it but still the view appear in the middle. can it be that android.R.id.content viewGroup dont cover entire screen only half? i can get it to display on the middle of the screen but not below it – Michael A Oct 25 '16 at 11:17

3 Answers3

8

The solution is to attach view to the root layout of the screen which can be achieved like this:

ViewGroup rootView = (ViewGroup) findViewById(android.R.id.content);

Essentially the root layout is FrameLayout and attaching view to bottom center of it can be achieved like this:

final FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT);
    params.gravity = Gravity.BOTTOM|Gravity.CENTER;
    testRoot.addView(dfpBanner, view);
Abhinav Tyagi
  • 5,158
  • 3
  • 30
  • 60
Michael A
  • 5,770
  • 16
  • 75
  • 127
2
 RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams( 
                                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                                    RelativeLayout.LayoutParams.WRAP_CONTENT);

The RelativeLayout you are adding will be taking whole width and height as parent layout.

Bills
  • 768
  • 7
  • 19
1

As your layout params is for child view only try making it's height as WRAP_CONTENT

RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
Kunu
  • 5,078
  • 6
  • 33
  • 61