[英]Retrieve the X & Y of FAB
I have a RelativeLayout and inside this layout i have fab button: 我有一个RelativeLayout,并且在此布局中有fab按钮:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="8dp"/>
Now , in java I want to now, where is the fab position on the screen.I used this method according this post : enter link description here 现在,在Java中我想现在在屏幕上的晶圆厂位置在哪里。我根据这篇文章使用了这种方法: 在此处输入链接描述
private Point getPointOfView(View view) {
int[] location = new int[2];
view.getLocationInWindow(location);
return new Point(location[0], location[1]);
}
and using this method like this: 并使用这种方法:
fab = findViewById(R.id.fab);
for (int i = 0; i < pv.length; i++) {
pv[i] = new Point(getPointOfView(fab).x ,getPointOfView(fab).y);
}
but getPointOfView(fab).x and getPointOfView(fab).y
return 0.how could i retrieve the X & Y fab button? 但是
getPointOfView(fab).x and getPointOfView(fab).y
返回0。如何检索X&Y fab按钮?
You can make use of View#post()
API, then your code would be replaced with this one: 您可以使用
View#post()
API,然后将您的代码替换为以下代码:
FloatingActionButton fab = findViewById(R.id.fab);
fab.post(new Runnable() {
@Override
public void run() {
// this callback will be executed after view is laid out
for (int i = 0; i < pv.length; ++i) {
pv[i] = new Point(getPointOfView(fab).x ,getPointOfView(fab).y);
}
}
})
use 采用
View.getLocationOnScreen()
method to get values. 获取值的方法。 Note: try to use this method in handler
注意:尝试在处理程序中使用此方法
new Handler ().post(...... v.getLocationOnScreen(location); .....);
onCreate method is to early to get location we should have to try this in onWindowFocusChanged()
method of activity when application end all the view related tasks. 当应用程序结束所有与视图相关的任务时,应尽早使用onCreate方法获取位置,我们应该在活动的
onWindowFocusChanged()
方法中尝试进行此操作。
I found, how could i get fab position: 我发现,如何获得晶圆厂的职位:
fab.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
for (int i = 0; i < pv.length; i++) {
pv[i] = new Point(getPointOfView(fab).x, getPointOfView(fab).y);
}
fab.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
but if i have mistake in removing GloabalLayout place please tel me. 但是,如果我在删除GloabalLayout位置时出错,请给我打电话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.