Android在控件绘图前改变宽高


在Activity的onCreate的时候

使用getWidth()和getHeight()的时候,获取的值为0

为了根据宽来动态调整高度

可以使用ViewTreeObserver的addOnPreDrawListener添加OnPreDrawListener

在函数onPreDraw()里修改高度

改完后做下重入判断,以免死循环


int finalHeight, finalWidth; final ImageView iv = (ImageView)findViewById(R.id.scaled_image); final TextView tv = (TextView)findViewById(R.id.size_label); ViewTreeObserver vto = iv.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { iv.getViewTreeObserver().removeOnPreDrawListener(this); finalHeight = iv.getMeasuredHeight(); finalWidth = iv.getMeasuredWidth(); tv.setText("Height: " + finalHeight + " Width: " + finalWidth); return true; } });



https://stackoverflow.com/questions/10411975/how-to-get-the-width-and-height-of-an-image-view-in-android

https://developer.android.com/reference/android/view/ViewTreeObserver.html



你可能感兴趣的:(android)