Reputation: 2430
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;
}
});
}
Upvotes: 5
Views: 5769
Reputation: 122
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
Upvotes: 1
Reputation: 6605
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.
Upvotes: 2