public void alignSheetWithFab ( View fab ) { // NOTE: View.getLocationOnScreen() returns the view's coordinates on the screen // whereas other view methods like getRight() and getY() return coordinates relative // to the view's parent. Using those methods can lead to incorrect calculations when // the two views do not have the same parent. // Get FAB's coordinates int [ ] fabCoords = new int [ 2 ] ; fab . getLocationOnScreen ( fabCoords ) ; // Get sheet's coordinates int [ ] sheetCoords = new int [ 2 ] ; sheet . getLocationOnScreen ( sheetCoords ) ; // NOTE: Use the diffs between the positions of the FAB and sheet to align the sheet. // We have to use the diffs because the coordinates returned by getLocationOnScreen() // include the status bar and any other system UI elements, meaning the coordinates // aren't representative of the usable screen space. int leftDiff = sheetCoords [ 0 ] - fabCoords [ 0 ] ; int rightDiff = ( sheetCoords [ 0 ] + sheet . getWidth ( ) ) - ( fabCoords [ 0 ] + fab . getWidth ( ) ) ; int topDiff = sheetCoords [ 1 ] - fabCoords [ 1 ] ; int bottomDiff = ( sheetCoords [ 1 ] + sheet . getHeight ( ) ) - ( fabCoords [ 1 ] + fab . getHeight ( ) ) ; // NOTE: Preserve the sheet's margins to allow users to shift the sheet's position // to compensate for the fact that the design support library's FAB has extra // padding within the view ViewGroup . MarginLayoutParams sheetLayoutParams = ( ViewGroup . MarginLayoutParams ) sheet . getLayoutParams ( ) ; // Set sheet's new coordinates (only if there is a change in coordinates because // setting the same coordinates can cause the view to "drift" - moving 0.5 to 1 pixels // around the screen) if ( rightDiff != 0 ) { float sheetX = sheet . getX ( ) ; // Align the right side of the sheet with the right side of the FAB if // doing so would not move the sheet off the screen if ( rightDiff <= sheetX ) { sheet . setX ( sheetX - rightDiff - sheetLayoutParams . rightMargin ) ; revealXDirection = RevealXDirection . LEFT ; } // Otherwise, align the left side of the sheet with the left side of the FAB else if ( leftDiff != 0 && leftDiff <= sheetX ) { sheet . setX ( sheetX - leftDiff + sheetLayoutParams . leftMargin ) ; revealXDirection = RevealXDirection . RIGHT ; } } if ( bottomDiff != 0 ) { float sheetY = sheet . getY ( ) ; // Align the bottom of the sheet with the bottom of the FAB if ( bottomDiff <= sheetY ) { sheet . setY ( sheetY - bottomDiff - sheetLayoutParams . bottomMargin ) ; revealYDirection = RevealYDirection . UP ; } // Otherwise, align the top of the sheet with the top of the FAB else if ( topDiff != 0 && topDiff <= sheetY ) { sheet . setY ( sheetY - topDiff + sheetLayoutParams . topMargin ) ; revealYDirection = RevealYDirection . DOWN ; } } }
Aligns the sheet s position with the FAB .