Mục tiêu
Xoay ImageView mượt mà bằng RotateAnimation với LinearInterpolator.
Các bước
Bước 1: Tạo project
Bước 2: Layout activity_main.xml
<LinearLayout ... android:gravity="center" android:orientation="vertical">
<TextView android:id="@+id/text" android:text="rotate image" android:textSize="18sp" android:textAlignment="center" android:layout_width="match_parent" android:layout_height="wrap_content" />
<ImageView android:id="@+id/rotateImage" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:src="@mipmap/ic_launcher" android:layerType="software" />
</LinearLayout>
Bước 3: MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView text;
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
image = findViewById(R.id.rotateImage);
text.setOnClickListener(v -> {
// Xoay từ 0° đến 180° quanh tâm
RotateAnimation rotate = new RotateAnimation(
0, 180,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f
);
rotate.setDuration(5000); // 5 giây
rotate.setInterpolator(new LinearInterpolator()); // Tốc độ đều
image.startAnimation(rotate);
});
}
}
Tham số RotateAnimation:
fromDegrees=0, toDegrees=180: Góc bắt đầu/kết thúc.pivotXType=RELATIVE_TO_SELF, pivotXValue=0.5f: Trục xoay X ở giữa (50% width).pivotYType=RELATIVE_TO_SELF, pivotYValue=0.5f: Trục xoay Y ở giữa (50% height).setDuration(5000): Thời gian animation (ms).LinearInterpolator: Tốc độ không đổi (mượt, không ease in/out).
Kết quả
Màn hình ban đầu:

Click text → Image xoay mượt 180° trong 5 giây:

Bổ sung
- Xoay 360°:
new RotateAnimation(0, 360, ...). - Xoay vô tận:
rotate.setRepeatCount(Animation.INFINITE). - XML animation: res/anim/rotate.xml →
AnimationUtils.loadAnimation(). - ViewPropertyAnimator (API 12+):
image.animate().rotation(180).setDuration(5000).setInterpolator(new LinearInterpolator())- đơn giản hơn.