使用场景可以为已经绘画出的view,想根据比例动态改变宽高。
public class ViewUtil {
public static void getViewWidth(final View view, final OnViewListener onViewListener) {
ViewTreeObserver vto2 = view.getViewTreeObserver();
vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
if(onViewListener!=null){
onViewListener.onView(view.getWidth(),view.getHeight());
}
}
});
}
public interface OnViewListener {
void onView(int width,int height);
}
}
使用方法:
ViewGroup.LayoutParams layoutParams1 = myView.getLayoutParams(); ViewUtil.getViewWidth(myView, new ViewUtil.OnViewListener() { @Override public void onView(int width, int height) { layoutParams1.width = width; layoutParams1.height = ((int) (width * 1.05)); myView.setLayoutParams(layoutParams1); } });