有没有办法处理视图可见性更改(例如,从GONE到VISIBLE)而不覆盖视图?
像View.setOnVisibilityChangeListener();
?
答案 0 :(得分:39)
您可以使用GlobalLayoutListener
来确定视图可见性是否有任何更改。
myView.setTag(myView.getVisibility());
myView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int newVis = myView.getVisibility();
if((int)myView.getTag() != newVis)
{
myView.setTag(myView.getVisibility());
//visibility has changed
}
}
});
答案 1 :(得分:3)
您可以使用装饰而不是子类:
class WatchedView {
static class Listener {
void onVisibilityChanged(int visibility);
}
private View v;
private Listener listener;
WatchedView(View v) {
this.v = v;
}
void setListener(Listener l) {
this.listener = l;
}
public setVisibility(int visibility) {
v.setVisibility(visibility);
if(listener != null) {
listener.onVisibilityChanged(visibility);
}
}
}
然后
WatchedView v = new WatchedView(findViewById(R.id.myview));
v.setListener(this);
答案 2 :(得分:2)
看看ViewTreeObserver.OnGlobalLayoutListener
。如文档中所述,当视图树中的全局布局状态或视图的可见性发生更改时,将调用其回调方法onGlobalLayout()
。因此,您可以尝试使用它来检测视图可见性何时发生变化。