java 创建 View 后运行一个方法 - Android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16297587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run a method after View is created - Android
提问by Waddas
I've currently got an activity that creates a view. this view uses other classes (such as one to create a random sequence of integers). I need to run a method (which will display the sequence using bitmaps) once the view is created. So once the user clicks "Start Game" this sequence will be displayed.
我目前有一个创建视图的活动。此视图使用其他类(例如创建随机整数序列的类)。创建视图后,我需要运行一个方法(它将使用位图显示序列)。因此,一旦用户单击“开始游戏”,就会显示此序列。
I've tried calling the method after setting the content view inside the onCreate method by the sequence is not generated (all 0's) correctly. I've tries this also with onStart and onFinishInflate inside the myView class.
我已经尝试在 onCreate 方法中设置内容视图后调用该方法,因为序列未正确生成(全部为 0)。我也在 myView 类中使用 onStart 和 onFinishInflate 尝试过这个。
Is there a way i can run this method after everything is inflated and initialized? So after the user clicks "Start Game" and the view is changed, the method needs to run.
有没有办法在一切都膨胀和初始化后运行这个方法?所以当用户点击“开始游戏”并改变视图后,该方法需要运行。
Thanks for looking.
谢谢你看。
Edit: A failed attempt.
编辑:失败的尝试。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.gameView = new GameView(getApplicationContext(), getCellSource(getApplicationContext()));
setContentView(this.gameView);
// this.gameView.displaySequence(this.gameView.gameEngine.getGenSequence()); Need this to run once view is displayed.
}
回答by Udi Oshi
Try using ViewTreeObserveras follow:
尝试使用ViewTreeObserver如下:
final View yourView = View.inflate(....);
ViewTreeObserver observer = yourView .getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// Do what you need with yourView here...
}
});
Notice that the function removeGlobalOnLayoutListener(this) is different in some sdk versions.
请注意,函数 removeGlobalOnLayoutListener(this) 在某些 sdk 版本中有所不同。