如何使观察者进入听众内部?
例:
ViewTreeObserver myObserver = myLayout.getViewTreeObserver();
myObserver.addOnPreDrawListener(new OnPreDrawListener() {
@Override
public boolean onPreDraw() {
// I want to get the myLayout or myObserver here,
// but I don't want to use the lines below
RelativeLayout myLayout = (RelativeLayout)findViewById(myId);
myLayout.getViewTreeObserver().removeOnPreDrawListener(this);
最佳答案
将其设为final或将其声明为实例变量,即在onCreate
之前声明并初始化onCreate
final ViewTreeObserver myObserver = myLayout.getViewTreeObserver();
http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#accessing
ViewTreeObserver.OnPreDrawListener是由匿名内部类实现的接口。因此要访问变量,必须为
final
。