在活动完全布局并为用户交互做好准备的时刻,会调用哪种方法?

saa*_*az1 27 android android-activity

我需要一种方法来在活动完全加载,布局,绘制并准备好用户的触摸控件的确切时刻运行一些代码.哪个方法/监听器可以做到这一点?

Sim*_*mon 27

Commonsware是对的,没有解释你想要做什么以及为什么,它不可能回答你的问题而我怀疑,你可能会以错误的方式思考问题.

但是,我确实有一些代码,我需要在测量完一切后做一些非常时髦的布局.

我可以扩展布局中的每个视图类并重写,onMeasure()但这将是很多工作.所以,我最终做到了这一点.不是很好,但它确实有效.

mainMenuLayout是我需要的布局.在onGlobalLayout当布局已经完成图纸回调被调用. Utils.setTitleText()是发生funkiness的地方,当我将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);
                    }

                }
            });
Run Code Online (Sandbox Code Playgroud)

  • 美丽的答案,少了第一段.为什么这种态度?这家伙已经清楚地透露了所有必需的输入.无论如何,在我添加到ListView的标题视图的情况下,ViewTreeObserver监听器没有做到这一点.它已经通过子类化View并覆盖其onLayout()方法,如上所述.有趣的是,该方法被调用两次,第一次调用实际上没有标题视图的布局. (6认同)

Jas*_*son 14

我发现如果我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
    }
} );
Run Code Online (Sandbox Code Playgroud)

我打电话后随时都能找到成功setContentView().


5hs*_*sba 0

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