Detect if an item is visible within a NestedScrollView on Android?

2

I need to detect if an element inside a scroll is being displayed on the screen.

On my test bench I have a text lorem impsum and then a button myBtn1

To detect when scrolling in NestedScrollView use

Button myBtn1 = (Button) findViewById(R.id.myBtn1);
NestedScrollView scroller = (NestedScrollView) findViewById(R.id.myScroll);
if (scroller != null) {

     scroller.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
         @Override
         public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

//aquí detectar si myBtn aparece en pantalla
         }
     });
 }

My idea is to obtain the top of the button and compare if the scrollY is higher to know that the button has been viewed, taking into account the height of the scroll element, as well as to see if the button has disappeared at the top .

I wonder if there is any function in Java to determine if an element is visible / drawn on the screen?

    
asked by Webserveis 07.06.2016 в 12:52
source

1 answer

1

Solved!

A quick way to detect an element is on screen is checking the rect bounds (top, right, bottom, left) of an element with the rect bounds of another.

Detect if it's on screen

If you need to detect if the button is showing on the screen or not:

if (myBtn1 != null) {

    if (myBtn1.getLocalVisibleRect(scrollBounds)) {
        Log.i(TAG, "Botón en pantalla");
    } else {
        Log.i(TAG, "No está en pantalla");
    }
}

Detect if it is on screen in its entirety

If you need to detect if the button is showing partially or completely within the screen

if (myBtn1 != null) {

    if (myBtn1.getLocalVisibleRect(scrollBounds)) {
        if (!myBtn1.getLocalVisibleRect(scrollBounds)
                || scrollBounds.height() < myBtn1.getHeight()) {
            Log.i(TAG, "Botón en pantalla - parcial");
        } else {
            Log.i(TAG, "Botón en pantalla - Total");
        }
    } else {
        Log.i(TAG, "No está en pantalla");
    }
}

Example:

final Button myBtn1 = (Button) findViewById(R.id.myBtn1);
final NestedScrollView scroller = (NestedScrollView) findViewById(R.id.myScroll);

if (scroller != null) {

    final Rect scrollBounds = new Rect();
    scroller.getHitRect(scrollBounds);

    scroller.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
        @Override
        public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

            if (myBtn1 != null) {

                if (myBtn1.getLocalVisibleRect(scrollBounds)) {
                    Log.i(TAG, "Botón en pantalla");
                } else {
                    Log.i(TAG, "No está en pantalla");
                }
            }

        }
    });
}
    
answered by 07.06.2016 / 13:16
source