28

我需要一种方法来在活动完全加载、布局、绘制并为用户的触摸控件做好准备的确切时刻运行一些代码。哪个方法/侦听器会这样做?

4

5 回答 5

28

Commonsware 是对的,如果不解释您要做什么以及为什么,就不可能回答您的问题,而且我怀疑,详细地说,您可能以错误的方式思考它。

但是,我确实有一些代码,在测量完所有内容后,我需要在其中做一些非常时髦的布局。

我本可以扩展布局中的每个视图类并覆盖onMeasure(),但这将是很多工作。所以,我最终这样做了。不是很好,但它有效。

mainMenuLayout 是我需要的布局。当onGlobalLayout布局完成绘制时调用回调。 Utils.setTitleText()是有趣的地方,当我将 mainMenuLayout 传递给它时,它可以访问所有子视图的位置和大小。

mainMenuLayout.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener() {

                @Override
                public void onGlobalLayout() {

                    // only want to do this once
                    mainMenuLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);

                    // set the menu title, the empty string check prevents sub-classes
                    // from blanking out the title - which they shouldn't but belt and braces!
                    if (!titleText.equals("")){
                        Utils.setTitleText(_context,mainMenuLayout,titleText);
                    }

                }
            });
于 2012-04-24T17:52:05.750 回答
17

我发现如果我将 a 发布Runnable到消息队列中,它将在活动的内容被绘制后运行。例如,如果我想要 a 的宽度和高度View,我会这样做:

view.post( new Runnable() {

    @Override
    public void run() {

        int width = view.getWidth(); // will be non-zero
        int height = view.getHeight(); // will be non-zero
    }
} );

我打电话后的任何时候都发现了这个成功setContentView()

于 2012-04-24T17:33:10.913 回答
0

onRestoreInstanceState方法是在onResume之后调用的用于恢复 UI 状态的方法。我认为您可以使用此 onRestoreInstanceState 方法..并在从 savedInstanceState 恢复 UI 状态后放置您的代码...

于 2012-04-24T17:27:03.740 回答
-1

Try onPostResume() called after onResume() at this moment the Activity instance should be visible and all underlying Views are rendered. In many situations this is true when onResume() is called as well.

于 2013-08-22T15:45:47.383 回答
-1

也许它没有什么帮助:

@Override
public void onAttachedToWindow(){}
于 2015-12-17T10:08:25.043 回答