在android中动态更改ImageView的位置

时间:2011-07-07 07:21:38

标签: android layoutparams

所有

我需要使用以下代码动态更改ImageView的位置

int x=100,y=100;
RelativeLayout.LayoutParams mparam = new RelativeLayout.LayoutParams((int)(LayoutParams.FILL_PARENT),(int)(LayoutParams.FILL_PARENT));
    mparam.topMargin=x;
    mparam.leftMargin=y;
    ball.setLayoutParams(mparam);
    x+=100;
    y+=100;

但我没有得到任何改变。

有可能吗?怎么样?

2 个答案:

答案 0 :(得分:4)

你改变了保证金,但不是它的位置,看起来,这不是一个好的解决方案。 尝试使用方法View.layout(int, int, int, int) Documentation说:

public void layout (int l, int t, int r, int b)

Since: API Level 1
Assign a size and position to a view and all of its descendants
This is the second phase of the layout mechanism. (The first is measuring). 
In this phase, each parent calls layout on all of its children to position them. 
This is typically done using the child measurements that were stored in 
the measure pass(). Derived classes should not override this method. Derived 
classes with children should override onLayout. In that method, they should call 
layout on each of their children.

Parameters

l   Left position, relative to parent
t   Top position, relative to parent
r   Right position, relative to parent
b   Bottom position, relative to parent

答案 1 :(得分:1)

您可以在View上调用setPadding。所以,在你的代码中(顺便说一下你应该放入代码块!),只需添加一个对这个方法的调用:

int x=100,y=100; 
LayoutParams mparam = new LayoutParams((int)(LayoutParams.FILL_PARENT),(int) (LayoutParams.FILL_PARENT));
ball.setLayoutParams(mparam); 
ball.setPadding(x,y,0,0);

x+=100; y+=100;
ball.setPadding(x,y,0,0);