Michael A Michael A - 1 month ago 8
Android Question

Programmatically add a View to the bottom of the screen

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

Answer

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 buttom 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);
Comments