5

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;
        }
    });
}
thd
  • 2,380
  • 1
  • 25
  • 33
  • Did you try this examples http://stackoverflow.com/questions/9073677/android-get-the-visible-area-of-a-view – vmtrue Jun 06 '14 at 09:33
  • If you have already tried something, you can better share this too. So we don't have to start from scratch. – ndsmyter Jun 06 '14 at 09:33

2 Answers2

2

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

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.

ndsmyter
  • 6,535
  • 3
  • 22
  • 37
1

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

tzanou
  • 122
  • 3