我有這個代碼:
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ObjectAnimator animX = ObjectAnimator.ofFloat(button3, "X", 0f, 50f);
ObjectAnimator animY = ObjectAnimator.ofFloat(button3, "Y", 0f, 50f);
AnimatorSet animSet = new AnimatorSet();
animSet.playSequentially(animX, animY);
animSet.setDuration(500);
animSet.start();
}
});
我正在嘗試使用 ObjectAnimator 在螢屏上隨機移動“button3”一段時間,但我不知道如何乘以 X 和 Y 值以使按鈕位置隨機。
uj5u.com熱心網友回復:
你可以這樣做。在我的示例中,我展示了按鈕僅在其容器內移動(id= parentView)并且不會超出它。我限制了寬度和高度,你可以改變你想要的值(或match_parent)
主要活動
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
FrameLayout parent = findViewById(R.id.parentView);
Random random = new Random();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
float randomX = (float) (random.nextInt(parent.getWidth() - button.getWidth()));
float randomY = (float) (random.nextInt(parent.getHeight() - button.getHeight()));
button.animate().x(randomX).y(randomY).setDuration(500).start();
}
});
}
}
活動_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@ id/parentView"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:background="@android:color/darker_gray">
<Button
android:id="@ id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
</FrameLayout>

uj5u.com熱心網友回復:
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int rx = new Random().nextInt(50);
int ry = new Random().nextInt(50);
ObjectAnimator animX = ObjectAnimator.ofFloat(button3, View.X, new Random().nextBoolean() ? rx : rx * -1);
ObjectAnimator animY = ObjectAnimator.ofFloat(button3, View.Y, new Random().nextBoolean() ? ry : ry * -1);
AnimatorSet animSet = new AnimatorSet();
animSet.playSequentially(animX, animY);
animSet.setDuration(500);
animSet.start();
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/372858.html
