gpt4 book ai didi

java - 如何监听多个 GlobalLayout 事件

转载 作者:行者123 更新时间:2023-12-03 14:46:32 26 4
gpt4 key购买 nike

我正在尝试收听 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事件。
目前我只是尝试使用 this question 来监听 View 位置的变化。
我试过 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>
如果布局在全局布局监听器中以某种方式被修改,那么它将触发另一个布局和另一个对监听器的调用。如果监听器再次进行更改,监听器将再次被调用,以此类推。
如果您发布遇到问题的实际代码或演示问题的简单项目,这将很有帮助。布局是否在监听器中以某种方式修改?

更新:正如您在对此答案的评论中所说的那样,您的问题是您对全局布局监听器中的 View 进行了更改,这触发了另一个布局和对监听器的无限调用。删除导致布局更改的代码后,该特定问题就解决了。

关于java - 如何监听多个 GlobalLayout 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65874844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com