无法在 Activity android 中以编程方式重新定位视图

Couldn't reposition views programatically in an Activity android

我在 Activity 中有 5 个按钮,具有相对布局。我有一个函数叫做 init() 将使用 setX()setY() 重新定位按钮。当我从 onClickListener 内部调用 init() 时,按钮重新排列没有任何问题。但是当我从 onCreate()onStart() 调用该函数时,日志显示该函数已执行但按钮保持不变位置。我该怎么办?

此外,如果我从 onResume() 调用 init(),按钮将毫无问题地重新定位。

public class MainActivity extends ActionBarActivity {
@Override
protected void onStart()
{
    super.onStart();
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //if init() is called here I can see the Log "Tag/Init Executed" but the buttons are not repositioned
}
@Override
protected void onResume()
{
    Log.i("Log", "resume called");
    super.onResume();
    //if i call init() here, the button is not repositioned but if i click home button and resume the app again, the button is repositioned.
}
public void init()
{
    Log.i("Tag","Init Executed");
    b1=(ImageButton)findViewById(R.id.imageButton);
    b1.setX(p.x);
    b1.setY(p.y);
}
}

onCreate():

首次创建 activity 时调用。这是您应该进行所有常规静态设置的地方:创建视图、将数据绑定到列表等。此方法还为您提供了一个包含 activity 先前冻结状态的 Bundle(如果有的话)。始终跟随 onStart()。

onRestart():

在您的 activity 停止后,再次启动之前调用。始终跟随 onStart()

onStart():

当 activity 对用户可见时调用。如果 activity 出现在前台,则紧随其后的是 onResume(),如果它被隐藏,则紧随其后的是 onStop()。

Android activity life cycle - what are all these methods for?

好的,我很久以前就解决了这个问题。刚刚有时间更新一下。使用它后对我有用。

View myView=view.findViewById(R.id.parent);
myView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
         init();
    }