作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试收听 GlobalLayout
使用
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
int c=0;
@Override
public void onGlobalLayout() {
c++; //without removing the listener c will grow for ever even though there is no GlobalLayout events
view.setText(""+c);
}
});
但它被无休止地调用。
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
但我想让听众在下一个
GlobalLayout
事件。
onPreDraw
但它是一样的。
GlobalLayout
事件?
最佳答案
由于访问变量 c
的问题,您作为示例发布的代码不应编译。来自听者。如果你尝试一下,你应该在 Android Studio 中得到以下错误:
Variable 'c' is accessed from within inner class, needs to be final or effectively final
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final int[] c = {0};
final View[] view = {findViewById(R.id.textView)};
view[0].getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
c[0]++;
}
});
}
}
如果您针对以下布局运行此代码,您将看到监听器被调用了两次,我认为这对应于两次布局传递:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>
如果布局在全局布局监听器中以某种方式被修改,那么它将触发另一个布局和另一个对监听器的调用。如果监听器再次进行更改,监听器将再次被调用,以此类推。
关于java - 如何监听多个 GlobalLayout 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65874844/
我正在尝试收听 GlobalLayout使用 view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnG
我是一名优秀的程序员,十分优秀!