开发者

how to find the view location in android

开发者 https://www.devze.com 2023-02-07 09:50 出处:网络
How can I find the view position in android? To get the position I used view.getLeft(), vie开发者_JS百科w.getRight(), view.getTop() and view.getBottm(). But these methods are returning 0 (Zero). I us

How can I find the view position in android?

To get the position I used view.getLeft(), vie开发者_JS百科w.getRight(), view.getTop() and view.getBottm(). But these methods are returning 0 (Zero). I used these methods after calling the setContentView() method.

If anyone know the code to get the view position, please help me.


This worked for me in 2.2:

custRegScrollView.smoothScrollTo(0, activity.findViewById(labelId)
            .getTop() - (viewHeight / 2) + offset);

The bit of the code you're looking for is:

int viewPos = activity.findViewById(R.id.myView).getTop();

This should return the following spot in a view's "rectangle"

 >______
  |    |
  |    |
  |____|

I.e., the Y (vertical) coordinate of the top of the view.

Note that this is contextual based on what kind of Layout you're using. This was tested in a ScrollView, as seen above.

Hope this helps!


Where were you calling getLeft(), getTop(), etc? A view's position isn't set until onMeasure() is called, and so those methods will return 0 until then. onCreate() is called sometime before onMeasure(), and so calling getLeft() won't be much use in onCreate(). You may want to move your code to onMeasure() or onResume(). If you do override onMeasure(), however, be aware that it is usually called several times.

0

精彩评论

暂无评论...
验证码 换一张
取 消