使用类似这样的布局(使用线性,亲属或其他布局,如果你愿意的话):
<LinearLayout
android:id="@+id/lty_parent">
<LinearLayout
android:id="@+id/lyt_first" />
<LinearLayout
android:id="@+id/lyt_second"/>
</LinearLayout>
然后在任何你想用它来控制它的onClick
方法,设置Visibility
和Gone.
之间Visible
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
布尔值的重置,现在添加它。
2 RelativeLayouts(上半部分+下半部分)在其他RelativeLayout(行)应该做的事情... + PCCoder评论:) – Selvin 2013-03-13 14:56:09
你试过[this](http://developer.android.com/reference/安卓/浏览/ View.html#setVisibility%28int 29%)? – PCoder 2013-03-13 14:56:12
基本上@Selvin说的是你应该在一个大** ViewGroup **(代表列表视图项)内部有2 ** ViewGroup **。在你的情况下,你所需要做的就是在** VISIBLE **和** GONE **之间设置第二个** ViewGroup **的可见性。 – Leeeeeeelo 2013-03-13 14:58:53