添加全局布局监听器即使没有附加监听器也会被调用,在这种情况下它会进入循环,我如何在不在循环中触发全局布局监听器的情况下编辑属性?谢谢
final View getDecorView = activity.getWindow().getDecorView();
getDecorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT > 16) {
getDecorView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
getDecorView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
final TextView textView3 = (TextView) decorView.findViewById(2131558456);
if (textView3 != null) {
textView3.setText("updated"); textView3.setBackgroundColor(Color.parseColor("#444444"));
}
getDecorView.getViewTreeObserver().addOnGlobalLayoutListener(this);
}
});
最佳答案
这种方法可以解决您的问题:
final View decorView = activity.getWindow().getDecorView();
final TextView textView3 = (TextView) decorView.findViewById(2131558456);
decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT > 16) {
decorView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
decorView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
if (textView3 != null && !textView3.getText().equals("updated")) {
textView3.setText("updated");
textView3.setBackgroundColor(Color.parseColor("#444444"));
}
decorView.getViewTreeObserver().addOnGlobalLayoutListener(this);
}
});
我假设 textview3
最初没有等于“updated”的文本,所以当您将其文本设置为“updated”时,它充当一种标志,这样您以后不要再设置了。您还可以执行以下操作,恕我直言,这更简洁一些,因为您有一个实际的 bool 标志,表示您是否应该更新 TextView
。
final View decorView = activity.getWindow().getDecorView();
final TextView textView3 = (TextView) decorView.findViewById(2131558456);
decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
boolean updateTextview = true;
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT > 16) {
decorView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
decorView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
if (textView3 != null && updateTextview) {
updateTextview = false;
textView3.setText("updated");
textView3.setBackgroundColor(Color.parseColor("#444444"));
}
decorView.getViewTreeObserver().addOnGlobalLayoutListener(this);
}
});
这两种解决方案都应该有效,因为它们停止了 textview3
的不断更新,这导致了另一个布局传递,导致了 textview3
的更新,这导致了另一个布局传递这导致……一直持续下去。
关于Android全局布局监听器在android中反复调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37116048/