Search code examples
javaandroidtextviewscrollviewandroid-toolbar

How to detect when TextView exits/enters screen on Android?


I have this LinearLayout with few elements in it. Since there are many elements I have wrap it inside ScrollView. Inside this LinearLayout I have one TextView element and I won't to detect when it is not longer visible on screen while scrolling.

The thing that I am trying to do is to show this Activity with LinearLayout and make title of toolbar empty, then when user scrolls down, and this TextView exits screen, I want to set title in the toolbar to content of that TextView. And similar when this text view enters screen again to set title in toolbar to be empty.

I have no idea how to implement this and what listeners to use...

EDIT:

This is what I want to create: detect when text view exits or enters screen and update title in toolbar accordingly.

enter image description here


Solution

  • This will work for API23 or higher, but it gives you the basic idea.

    ScrollView scroll = (ScrollView) findViewById(R.id.yourScrollView);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        scroll.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                Log.e(TAG, "SCROLL = " + scrollY);
                if(scrollY > txtView_Y){
                    setTitle("Hello");
                }
                else{
                    setTitle("I'm not there yet");
                }
            }
        });
    }
    

    The value txtView_Y is the y position of your TextView. You will have to get that after the Activity has positioned all the views. You will probably need ViewTreeObserver.OnGlobalLayoutListener for that.