简体   繁体   中英

Programmatically set the position of a view on Pre-Honeycomb devices

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM