使用类似这样的布局(如果您愿意,可以使用线性、相对或其他布局):
<LinearLayout
android:id="@+id/lty_parent">
<LinearLayout
android:id="@+id/lyt_first" />
<LinearLayout
android:id="@+id/lyt_second"/>
</LinearLayout>
然后在onClick
任何你想用来控制它的方法中,设置Visibility
介于Visible
和Gone.
public void buttonClickListener(){
((Button) findViewById(R.id.your_button))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (lyt_second.getVisibility() == View.GONE) {
lyt_second.setVisibility(View.VISIBILE);
}
else {
lyt_second.setVisibility(View.GONE);
}
});
如果您只想简单地出现/消失而没有什么花哨的,那很好。如果你想为它制作动画,事情会变得有点复杂,因为你需要使用负边距来让它看起来像这样增长和缩小:
我们使用与onClick
之前相同的方法,但这次当我们单击它时,会启动SlideAnimation
隐藏/可见视图的自定义。
@Override
public void onClick(View v) {
SlideAnimation slideAnim = new SlideAnimation(lyt_second, time);
lyt_second.startAnimation(slideAnim);
}
的实现SlideAnimation
基于一个通用Animation
类,我们对其进行扩展然后覆盖转换。
public SlideAnimation(View view, int duration) {
//Set the duration of the animation to the int we passed in
setDuration(duration);
//Set the view to be animated to the view we passed in
viewToBeAnimated = view;
//Get the Margin Parameters for the view so we can edit them
viewMarginParams = (MarginLayoutParams) view.getLayoutParams();
//If the view is VISIBLE, hide it after. If it's GONE, show it before we start.
hideAfter = (view.getVisibility() == View.VISIBLE);
//First off, start the margin at the bottom margin we've already set.
//You need your layout to have a negative margin for this to work correctly.
marginStart = viewMarginParams.bottomMargin;
//Decide if we're expanding or collapsing
if (marginStart == 0){
marginEnd = 0 - view.getHeight();
}
else {
marginEnd = 0;
}
//Make sure the view is visible for our animation
view.setVisibility(View.VISIBLE);
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
if (interpolatedTime < 1.0f) {
// Setting the new bottom margin to the start of the margin
// plus the inbetween bits
viewMarginParams.bottomMargin = marginStart
+ (int) ((marginEnd - marginStart) * interpolatedTime);
// Request the layout as it happens so we can see it redrawing
viewToBeAnimated.requestLayout();
// Make sure we have finished before we mess about with the rest of it
} else if (!alreadyFinished) {
viewMarginParams.bottomMargin = marginEnd;
viewToBeAnimated.requestLayout();
if (hideAfter) {
viewToBeAnimated.setVisibility(View.GONE);
}
alreadyFinished = true;
}
hideAfter = false;
}
}
编辑:如果有人以前使用过此代码并发现如果您在动画完成之前多次单击启动动画的按钮,那么它会从那时起弄乱动画,导致它总是在之后隐藏视图动画完成。我错过了hideAfter
代码底部附近布尔值的重置,现在添加它。