View相关知识的思考

思考一个问题:
将一个View添加到一个ViewGroup中,但是却不给该View分配足够的高度。当屏幕下拉时,动态调整该View的高度,使其能够实现上下移动显示或隐藏的效果。

涉及到的问题:

  1. 给View分配的高度为0:
addView(mContainer, new LayoutParams(LayoutParams.MATCH_PARENT, 0));
  1. 设置该View在ViewGroup中的Gravity
    (1) Bottom: View始终ViewGroup的底部,随着高度变大,逐渐往上窜;
    (2) Top: View始终在ViewGroup的顶部, 随着高度变大,逐渐往下伸;
setGravity(Gravity.BOTTOM);
  1. 设置该View自身的Gravity
    (1) Bottom: View的内容始终在自身区域的最底部,不管其高度如何;
    (2) Top: View的内容始终在自身区域的最顶部,不管其高度如何;
view.setGravity(Gravity.BOTTOM);
  1. getMeasuredHeight和getHeight的区别
    MeasuredHeight—how big a view wants to be within its parent.
    Height—Actual size on screen, at drawing time and after layout.

(1) 何时调用getMeasuredHeight?
在自定义View的Constructor中,调用measure()方法之后,可以拿到getMeasuredHeight()。

measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
mMeasuredHeight = getMeasuredHeight();

何时调用getHeight() ?
使用Handler post一个Runnable:

new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                int height = getHeight();
            }
}, 100);
  1. 动态调整View的高度
ViewGroup.LayoutParams layoutParams = mView.getLayoutParams();
layoutParams.height = (int) v;
mView.setLayoutParams(layoutParams);

你可能感兴趣的:(View相关知识的思考)