Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a view is partly off-screen

Tags:

android

I have a view that is added dynamically. Sometimes, the view is only partly visible since its bottom is off the screen. In this case, I want to move the view up. However, I don't know how to detect whether it is offscreen or not and by how much.

Edit: the context for this problem is that I have an edittext that I want to show a custom soft keyboard right next to it. Here is the code that I use to move the custom keyboard.

 public void moveKeyboardNextToView(View view) {
    int[] location = new int[]{0, 0};
    view.getLocationInWindow(location);
    Rect r = new Rect();
    view.getGlobalVisibleRect(r);

    int height = r.bottom - r.top;
    int newTop = r.bottom - view.getHeight() / 2 - this.mKeyboardView.getHeight() / 2;
    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) this.mKeyboardView.getLayoutParams();
    params.setMargins(0, newTop, 0, 0);
    this.mKeyboardView.setLayoutParams(params);
    this.mKeyboardView.invalidate();

    this.mKeyboardView.post(new Runnable() {
        @Override
        public void run() {
            int[] location = new int[2];
            Rect r2 = new Rect();
            mKeyboardView.getLocalVisibleRect(r2);
            double abc = r2.bottom;
        }
    });
}
like image 257
thd Avatar asked Oct 21 '22 07:10

thd


2 Answers

The way I would do this is, is by calculating it with the following info:

  • the location of the view on screen (getLocationOnScreen(int[]))
  • the width/height of the view (getMeasuredHeight() and getMeasuredWidth())
  • the width/height of the screen

If you have this information, it isn't that difficult anymore to calculate everything you need. Just make sure that you are using the same units (pixels, dpis etc) for every value.

like image 197
ndsmyter Avatar answered Oct 23 '22 04:10

ndsmyter


its kind of a late answer but for future reference I created a library for this purpose.If your view is inside a scrollview you can use my library

It adds an onScrollChangedListener from ViewTreeObserver and every time scroll changes recalculates the visible percentage of the view and calls a custom listener.

You can find it here : PercentVisibleLayout

like image 31
tzanou Avatar answered Oct 23 '22 04:10

tzanou