Get Center point in my app android
In my app Horizontalscrollview is present. It consist of LinearLayout in it, to that layout i have added number of buttons to it.ViewFlipper is also pr开发者_C百科esent in it. As i flip the layout i want to move the horizontalscrollview the respective button should get to center position. My layout(s) and number of button(s) are same. for 1st layout 1st button should be at center location?
thnx for any help....
Hmm, okay, just to point out, when you get to the first or last position (possibly first + 1, last - 1 as well, depending on the button size), you won't be able to have it in the center, as you can't overscroll with just a HorizontalScrollView. With that in mind, for your general case (you can handle the edge cases however you like -- I'd suggest just leaving it scrolled as far as you can, and giving the selected button some sort of highlight) you should be able to do something like this:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int screenWidth = metrics.widthPixels;
//get an instance of your LinearLayout, HSV, and ViewFlipper
LinearLayout ll = (LinearLayout)findViewById(R.id.my_linear_layout);
ViewFlipper vf = (ViewFlipper)findViewById(R.id.my_view_flipper);
HorizontalScrollView hsv = (HorizontalScrollView)findViewById(R.id.my_hsv);
//as you've said, there should always be an equal number of Buttons as
//Views in the ViewFlipper. This code assumes that is always true.
View v = ll.getChildAt(vf.getDisplayedChild());
//assuming smoothScrollTo scrolls to the left side of the screen,
//which I think it does, we want to scroll to the Button's center
//point, minus (shifted to the right) by half the screen width
int scrollTo = v.getLeft() + (v.getWidth() - screenWidth) / 2);
//handle overflow for the edge cases
if (scrollTo < 0) scrollTo = 0;
else if (scrollTo > hsv.getWidth()) scrollTo = hsv.getWidth();
hsv.smoothScrollTo(scrollTo);
Untested, and I'm prone to small syntax errors, but the general idea may help. :)
Get the size of Display, and divide by 2, then subtract your button width divided by 2 ?
But it really sounds like you should have the buttons in its own view, then merge the views on top of each other.
<merge>
<HorizontalScrollView .../>
<Button ... />
</merge>
精彩评论