我可以用动画隐藏Android控件吗?

时间:2011-12-07 20:54:58

标签: android animation android-edittext

我有一个Android视图,其中包含一个带有三个RadioButton的RadioGroup。当选择其中一个RadioButtons时,用户还必须在EditText控件中输入文本。如果选择了其他两个RadioButtons中的任何一个,则不需要此额外信息。

我目前正在使用RadioGroup的OnCheckedChangedListener来确定何时检查新的RadioButton,并通过将其可见性设置为View.GONE来隐藏EditText。然而,这有点不和谐,我想知道是否有一种方法可以让转换动画。这是可能的,如果是这样,那么开始的关键是什么?

2 个答案:

答案 0 :(得分:1)

由于您使用的是API级别7,因此不再适用答案LayoutTransition。

请参阅文章:How can I set an entire view's alpha value in api level 7 (Android 2.1)

答案 1 :(得分:1)

我提出了以下可行的解决方案,该解决方案基于我在http://tech.chitgoks.com/2011/10/29/android-animation-to-expand-collapse-view-its-children/找到的代码

在我的活动中:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.edit_account);
    companyGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId)
        {
            if (checkedId == R.id.companyRadio)
                EDNUtils.expandCollapse(companyNameText, true, 500);
            else
                EDNUtils.expandCollapse(companyNameText, false, 500);
        }
    });
}

EDNUtils的实施:

public static Animation expandCollapse(final View v, final boolean expand) 
{       
    return expandCollapse(v, expand, 1000);
}

public static Animation expandCollapse(final View v, final boolean expand, final int duration) 
{
    int currentHeight = v.getLayoutParams().height;
    v.measure(MeasureSpec.makeMeasureSpec(((View)v.getParent()).getMeasuredWidth(), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    final int initialHeight = v.getMeasuredHeight();

    if ((expand && currentHeight == initialHeight) || (!expand && currentHeight == 0))
        return null;

    if (expand) 
        v.getLayoutParams().height = 0;
    else 
        v.getLayoutParams().height = initialHeight;
    v.setVisibility(View.VISIBLE);

    Animation a = new Animation() 
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) 
        {
            int newHeight = 0;
            if (expand) 
                newHeight = (int) (initialHeight * interpolatedTime);
            else 
                newHeight = (int) (initialHeight * (1 - interpolatedTime));
            v.getLayoutParams().height = newHeight;            
            v.requestLayout();

            if (interpolatedTime == 1 && !expand)
                v.setVisibility(View.GONE);
        }

        @Override
        public boolean willChangeBounds()  
        {
            return true;
        }
    };
    a.setDuration(duration);
    v.startAnimation(a);
    return a;
}