Android展开/折叠网格视图

时间:2014-10-13 16:04:23

标签: android animation gridview

我想扩展并完成GridView。当我扩展一切顺利,然后我崩溃,一切都很好,问题是当我回去扩展时,只显示一行。

我的GridView:

public class MyGridView extends GridView {

 public MyGridView(Context context) {
        super(context);
    }

    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setVisibility(int visibility) {
        // TODO Auto-generated method stub
        super.setVisibility(visibility);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightSpec;

        if (getLayoutParams().height == LayoutParams.WRAP_CONTENT) {

            heightSpec = MeasureSpec.makeMeasureSpec(
                    Integer.MAX_VALUE >>2, MeasureSpec.AT_MOST);
        }
        else {
            // Any other height should be respected as is.
            heightSpec = heightMeasureSpec;
        }

        super.onMeasure(widthMeasureSpec, heightSpec);
    }


}

展开/折叠:

private void expand() {
     //set Visible
    gridview.setVisibility(View.VISIBLE);

     final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
     final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
     gridview.measure(widthSpec, heightSpec);

     ValueAnimator mAnimator = slideAnimator(0, gridview.getMeasuredHeight());
     mAnimator.start();
}

private void collapse() {
     int finalHeight = gridview.getHeight();

     ValueAnimator mAnimator = slideAnimator(finalHeight, 0);

     mAnimator.addListener(new Animator.AnimatorListener() {
          @Override
          public void onAnimationEnd(Animator animator) {
             //Height=0, but it set visibility to GONE
              gridview.setVisibility(View.GONE);
          }

        ...

     });
     mAnimator.start();
}



private ValueAnimator slideAnimator(int start, int end) {

    ValueAnimator animator = ValueAnimator.ofInt(start, end);

    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
         @Override
         public void onAnimationUpdate(ValueAnimator valueAnimator) {
            //Update Height
            int value = (Integer) valueAnimator.getAnimatedValue();
            ViewGroup.LayoutParams layoutParams = gridview.getLayoutParams();
            layoutParams.height = value;
            gridview.setLayoutParams(layoutParams);
         }
    });
    return animator;
}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我通过向GridView添加GlobalLayoutListener解决了这个问题,存储了高度并在展开时替换了:

 ValueAnimator mAnimator = slideAnimator(0, gridview.getMeasuredHeight());

使用:

  ValueAnimator mAnimator = slideAnimator(0, STORED_HEIGHT);