Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách hiển thị Button tại vị trí ngẫu nhiên trên màn hình Android

Giới thiệu

Ví dụ này minh họa cách di chuyển một Button đến vị trí ngẫu nhiên trên màn hình mỗi giây, sử dụng Timer, Handler và animation thuộc tính (property animation).

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio → File → New Project → chọn Empty Activity → đặt tên → Finish.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/my_button"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="Bấm tôi"
        android:layout_gravity="top|start" />

</FrameLayout>

Lưu ý: Dùng FrameLayout hoặc ConstraintLayout để cho phép đặt tọa độ X, Y tự do cho Button. Ví dụ gốc dùng LinearLayout với layout_x/layout_y không hoạt động đúng.

Bước 3: Logic chính (src/MainActivity.java)

package com.example.myapplication;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends FragmentActivity {

    private Button button;
    private Timer timer;
    private Random random = new Random();
    private int screenWidth, screenHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = findViewById(R.id.my_button);

        // Lấy kích thước màn hình
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;

        // Trừ đi kích thước button để không bị tràn màn hình
        button.post(() -> {
            int btnW = button.getWidth();
            int btnH = button.getHeight();
            screenWidth -= btnW;
            screenHeight -= btnH;
        });

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> moveButtonRandomly());
            }
        }, 0, 1000); // Mỗi 1 giây
    }

    private void moveButtonRandomly() {
        if (screenWidth <= 0 || screenHeight <= 0) return;

        float newX = random.nextInt(screenWidth);
        float newY = random.nextInt(screenHeight);

        button.animate()
                .x(newX)
                .y(newY)
                .setDuration(500) // Animation mượt 500ms
                .start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer.purge();
        }
    }
}

Cải tiến so với ví dụ gốc:

  • Dùng FrameLayout cho phép đặt tọa độ tự do.
  • Tính toán kích thước màn hình trừ kích thước button để không bị tràn ra ngoài.
  • Thêm animation mượt mà (500ms) thay vì setDuration(0).
  • Hủy Timer trong onDestroy() tránh rò rỉ tài nguyên.
  • Khởi tạo Random một lần, không tạo mới mỗi lần chạy.

Bước 4: Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Button sẽ nhảy liên tục đến các vị trí ngẫu nhiên mỗi giây.

Cách hiển thị Button tại vị trí ngẫu nhiên trên màn hình Android

Cách hiển thị Button tại vị trí ngẫu nhiên trên màn hình Android

Cách hiển thị Button tại vị trí ngẫu nhiên trên màn hình Android