简体   繁体   English

以编程方式在蜂窝状设备上设置视图的位置

[英]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 : 我正在尝试使用以下代码在Android上以编程方式设置视图的位置:

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. 它可以在我的Nexus 7和Motorola G设备上使用,但不能在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: XML代码:

<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 : Java代码:

    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. 一开始,我使用FrameLayout而不是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. 如果父级布局是FrameLayout,则似乎无法通过Android 2.2以编程方式设置视图的位置。

Thanks a lot for your help. 非常感谢你的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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