Giới thiệu
Ví dụ này minh họa cách show/hide một View (LinearLayout chứa form đăng nhập) với animation trượt lên/xuống (slide up/down) bằng TranslateAnimation.
Bước 1: Tạo dự án mới
Android Studio → File → New Project.
Bước 2: Giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:layout_width="150dp"
android:text="Toggle"
android:layout_height="wrap_content"/>
<LinearLayout
android:id="@+id/view"
android:background="#A6E1AA"
android:orientation="vertical"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_margin="20dp"
android:layout_height="200dp">
<EditText
android:hint="Tên đăng nhập"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:hint="Mật khẩu"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
Bước 3: Logic slide (src/MainActivity.java)
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
boolean opened = false;
LinearLayout view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = findViewById(R.id.view);
view.setVisibility(View.INVISIBLE);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!opened) {
// SHOW: Slide up từ dưới lên
view.setVisibility(View.VISIBLE);
TranslateAnimation animate = new TranslateAnimation(
0, 0, // fromX, toX
view.getHeight(), 0 // fromY, toY
);
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
} else {
// HIDE: Slide down từ trên xuống
TranslateAnimation animate = new TranslateAnimation(
0, 0,
0, view.getHeight()
);
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
view.setVisibility(View.INVISIBLE);
}
opened = !opened;
}
});
}
}
Giải thích TranslateAnimation
| Tham số | Show (Slide Up) | Hide (Slide Down) |
|---|---|---|
| fromX | 0 | 0 |
| toX | 0 | 0 |
| fromY | view.getHeight() | 0 |
| toY | 0 | view.getHeight() |