方式:
方式1:监听,如setOnClickListener
方式2:监听,如addOnGlobalLayoutListener
方式3:view.post 或 view.postdelay
方式4:onWindowFocusChanged
方式5:
示例:
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取view的宽高" />
</LinearLayout>
代码:
public class MyActivity extends FragmentActivity {
private Button btn;
private int mHeight;
private int mMeasuredHeight;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test3);
btn = ((Button) this.findViewById(R.id.btn));
mHeight = btn.getHeight();
mMeasuredHeight = btn.getMeasuredHeight();
Log.e("111", "onCreate==" + mHeight + " | " + mMeasuredHeight);//onCreate==0 | 0
//方式1:监听,如setOnClickListener
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHeight = btn.getHeight();
mMeasuredHeight = btn.getMeasuredHeight();
Log.e("111", "onClick==" + mHeight + " | " + mMeasuredHeight);//onClick==144 | 144
}
});
//方式2:监听,如addOnGlobalLayoutListener
btn.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onGlobalLayout() {
btn.getViewTreeObserver().removeOnGlobalLayoutListener(this);
mHeight = btn.getHeight();
mMeasuredHeight = btn.getMeasuredHeight();
Log.e("111", "onGlobalLayout==" + mHeight + " | " + mMeasuredHeight);//onGlobalLayout==144 | 144
}
});
//方式3:view.post
btn.post(new Runnable() {
@Override
public void run() {
mHeight = btn.getHeight();
mMeasuredHeight = btn.getMeasuredHeight();
Log.e("111", "post==" + mHeight + " | " + mMeasuredHeight);//post==144 | 144
}
});
}
@Override
protected void onResume() {
super.onResume();
mHeight = btn.getHeight();
mMeasuredHeight = btn.getMeasuredHeight();
Log.e("111", "onResume==" + mHeight + " | " + mMeasuredHeight);//onResume==0 | 0
}
@Override
protected void onStart() {
super.onStart();
mHeight = btn.getHeight();
mMeasuredHeight = btn.getMeasuredHeight();
Log.e("111", "onStart==" + mHeight + " | " + mMeasuredHeight);//onStart==0 | 0
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mHeight = btn.getHeight();
mMeasuredHeight = btn.getMeasuredHeight();
Log.e("111", "onWindowFocusChanged==" + mHeight + " | " + mMeasuredHeight);//onWindowFocusChanged==144 | 144
}
}
打印log顺序:
onCreate==0 | 0
onStart==0 | 0
onResume==0 | 0
onGlobalLayout==144 | 144
post==144 | 144
onWindowFocusChanged==144 | 144