如何让侦听器内的观察者? 例如:
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);
答案 0 :(得分:1)
我试过玩侦听器实例, 我不知道它有多准确,但它有效:)
final class MyOnPreDrawListener implements OnPreDrawListener
{
private RelativeLayout myLayout;
public void setMyLayout(RelativeLayout layout){
myLayout = layout;
}
@Override
public boolean onPreDraw() {
// now I have myLayout here
return true;
}
}
然后我打电话给
ViewTreeObserver observer = myLayout.getViewTreeObserver();
MyOnPreDrawListener myListener = new MyOnPreDrawListener();
myListener.setMyLayout(myLayout);
observer.addOnPreDrawListener(myListener);
答案 1 :(得分:0)
将其设为最终或将其声明为实例变量,即在onCreate
之前声明并初始化onCreate
final ViewTreeObserver myObserver = myLayout.getViewTreeObserver();
http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#accessing
ViewTreeObserver.OnPreDrawListener是由匿名内部类实现的接口。要访问变量,必须final
。