1

I am trying to programmatically set the position of a view on Android with the following code :

LayoutParams layoutParams = new LayoutParams(100, 100);
layoutParams.leftMargin = 200;
layoutParams.topMargin = 200;
myView.setLayoutParams( layoutParams ); 

It works on my Nexus 7 and Motorola G devices but not on old devices under Android 2.2. On these devices the view is alway set at the top left position of the screen.

How can I do the same thing on these devices ?

bobotetete
  • 11
  • 2
  • possible duplicate of [How can I dynamically set the position of view in Android?](http://stackoverflow.com/questions/6535648/how-can-i-dynamically-set-the-position-of-view-in-android) – romtsn Nov 29 '14 at 18:37
  • another for `API 8` : http://stackoverflow.com/questions/12195768/android-use-of-view-setx-and-sety-in-api-8 – Riad Nov 29 '14 at 19:10

1 Answers1

0

Here is the solution.

The XML code:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id = "@+id/rootView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</RelativeLayout>

The Java code :

    View myView = new View(this);
    LayoutParams layoutParams=new LayoutParams(320,240);
    layoutParams.leftMargin = 50;
    layoutParams.topMargin = 60;
    myView.setLayoutParams(layoutParams);
    myView.setBackgroundColor(Color.YELLOW);
    rootView.addView( myView );

    View myView2 = new View(this);
    layoutParams=new LayoutParams(320,240);
    layoutParams.leftMargin = 200;
    layoutParams.topMargin = 120;
    myView2.setLayoutParams(layoutParams);
    myView2.setBackgroundColor(Color.BLUE);
    rootView.addView( myView2 );

And we need to import

import android.widget.RelativeLayout.LayoutParams;

At the beginning I used FrameLayout instead of RelativeLayout. It seems it is not possible to programmatically set the position of a view with Android 2.2 if the parent layout is a FrameLayout.

Thanks a lot for your help.

bobotetete
  • 11
  • 2