public class CarJumpActivity extends Activity {
private ImageView iv1, iv2;
private int[] location1, location2;
private CarJumpView jumpview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_car_jump);
iv1 = (ImageView) findViewById(R.id.iv1);
jumpview=(CarJumpView)findViewById(R.id.jumpview);
iv2 = (ImageView) findViewById(R.id.iv2);
location1 = new int[2];
location2 = new int[2];
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
final int width = wm.getDefaultDisplay().getWidth();
final int height = wm.getDefaultDisplay().getHeight();
//具体方法post一个runnable对象
iv1.post(new Runnable() {
@Override
public void run() {
iv1.getLocationOnScreen(location1);
}
});
//具体方法
iv2.post(new Runnable() {
@Override
public void run() {
iv2.getLocationOnScreen(location2);
}
});
iv2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
jumpview.startJump(location2[0],location2[1],height);
}
});
iv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
jumpview.startJump(location1[0],location1[1],height);
}
});
}
@Override
protected void onResume() {
super.onResume();
// iv1.getLocationOnScreen(location1);
// iv2.getLocationOnScreen(location2);
// Log.i("onion",location1[0]+" "+location1[1]+" "+location2[0]+" "+location2[1]);
}
}
在onCreate()方法中想通过getLocationOnScreen()获取两个按钮在屏幕上的坐标,结果都为(0,0);锁屏之后重新执行onResume()方法就能获取确定的坐标点:
原因:Activity.onCreate(…)、onResume()方法中都没有办法获取到View的实际宽高,根本原因是控件还没有完成绘制。OnResume onPreDraw() 表示绘制的开始
网上给出的解决办法有多种,个人觉得最好用的一种就是:
将一个runnable添加到Layout队列中:View.post()
UI事件队列会按顺序处理事件。在setContentView()被调用后,事件队列中会包含一个要求重新layout的message,所以任何你post到队列中的东西都会在Layout发生变化后执行。runnable对象中的方法会在View的measure、layout等事件后触发。
两外有一种方法:获取固定宽高
View.getMeasureWidth()
View.getMeasureHeight()
有助于对个人对MeasureSpec的理解:
View的大小由width和height决定。一个View实际上同时有两种width和height值。
第一种是measure width和measure height。他们定义了view想要在父View中占用多少width和height(详情见Layout)。measured height和width可以通过getMeasuredWidth() 和 getMeasuredHeight()获得。
第二种是width和height,有时候也叫做drawing width和drawing height。这些值定义了view在屏幕上绘制和Layout完成后的实际大小。这些值有可能跟measure width和height不同。width和height可以通过getWidth()和getHeight获得。