2011-05-08 71 views

回答

12

解决方案:

private static int measureViewHeight(View view2Expand, View view2Measure) { 
    try { 
     Method m = view2Measure.getClass().getDeclaredMethod("onMeasure", int.class, int.class); 
     m.setAccessible(true); 
     m.invoke(view2Measure, 
        MeasureSpec.makeMeasureSpec(view2Expand.getWidth(), MeasureSpec.AT_MOST), 
        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); 
    } catch (Exception e) { 
     return -1; 
    } 

    int measuredHeight = view2Measure.getMeasuredHeight(); 
    return measuredHeight; 
} 

static public void expandOrCollapse(View view2Expand, View view2Measure, 
     int collapsedHeight) { 
    if (view2Expand.getHeight() < collapsedHeight) 
     return; 

    int measuredHeight = measureViewHeight(view2Expand, view2Measure); 

    if (measuredHeight < collapsedHeight) 
     measuredHeight = collapsedHeight; 

    final int startHeight = view2Expand.getHeight(); 
    final int finishHeight = startHeight <= collapsedHeight ? 
      measuredHeight : collapsedHeight; 

    view2Expand.startAnimation(new ExpandAnimation(view2Expand, startHeight, finishHeight)); 
} 

class ExpandAnimation extends Animation { 
    private final View _view; 
    private final int _startHeight; 
    private final int _finishHeight; 

    public ExpandAnimation(View view, int startHeight, int finishHeight) { 
     _view = view; 
     _startHeight = startHeight; 
     _finishHeight = finishHeight; 
     setDuration(220); 
    } 

    @Override 
    protected void applyTransformation(float interpolatedTime, Transformation t) { 
     final int newHeight = (int)((_finishHeight - _startHeight) * interpolatedTime + _startHeight); 
     _view.getLayoutParams().height = newHeight; 
     _view.requestLayout(); 
    } 

    @Override 
    public void initialize(int width, int height, int parentWidth, int parentHeight) { 
     super.initialize(width, height, parentWidth, parentHeight); 
    } 

    @Override 
    public boolean willChangeBounds() { 
     return true; 
    } 
}; 
+3

你可以给更多的细节,如何回调measureViewHeight()什么是浏览view2Expand,查看view2Measure? – pengwang 2011-05-23 02:19:49

+2

当然。在我的情况下,view2Measure - 是TextView。 view2Expand - 包含TextView的FrameLayout。我们测量文本视图的全部高度并将其应用于FrameLayout。当文本被折叠时,FrameLayout被用于淡入淡出效果(请参阅http://stackoverflow.com/questions/5947758/force-fading-edge-drawing) – HighFlyer 2011-05-29 16:52:57

+0

@HighFlyer你可以发布更多关于如何实现所有这些功能吗?你做了 – ingsaurabh 2011-09-30 08:07:30