如何监听多个 GlobalLayout 事件

ATP*_*ATP 6 java android listener

我正在尝试聆听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);
    }
});
Run Code Online (Sandbox Code Playgroud)

但它被无休止地调用。


我知道我应该像这样删除监听器: view.getViewTreeObserver().removeOnGlobalLayoutListener(this);

但我想让听众在接下来的GlobalLayout事件中保持活跃。

目前我只是尝试使用 我尝试过的这个问题来监听视图位置的变化,onPreDraw但它是一样的。


是否可以监听多个GlobalLayout事件?



提前致谢。

Che*_*amp 1

由于c从侦听器访问变量时出现问题,您作为示例发布的代码不应编译。如果您尝试这样做,您应该在 Android Studio 中收到以下错误:

变量“c”是从内部类内部访问的,需要是最终的或有效的最终

我们可以采用错误检查建议的建议并创建一个单元素数组,如下所示:

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]++;
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您针对以下布局运行此代码,您将看到侦听器被调用两次,我认为这对应于两个布局传递:

<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>
Run Code Online (Sandbox Code Playgroud)

如果在全局布局侦听器中以某种方式修改了布局,那么它将触发另一个布局并再次调用侦听器。如果侦听器再次进行更改,则侦听器将再次被调用,依此类推。

如果您发布遇到问题的实际代码或演示该问题的简单项目,将会很有帮助。布局是否在侦听器中以某种方式进行了修改?


更新:正如您在对此答案的评论之一中所说,您的问题是您对全局布局侦听器中的视图进行了更改,这触发了另一个布局以及对侦听器的另一个调用。一旦删除了导致布局更改的代码,该特定问题就得到了解决。