レイアウトとして次のようなものを使用します(必要に応じて、線形、相対、またはその他のレイアウトを使用します)。
<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
コードの下部近くにあるブール値のリセットを見逃しました。今すぐ追加しました。