我正在尝试使用加速度计为我的骰子应用按下android studio中的按钮。有谁知道如何将其连接到按钮,以便当我摇动手机时骰子会滚动吗?我尝试使用SensorEventListener,但无法正常工作。感谢您的任何反馈/建议。 PS。我是菜鸟。
这是我的Java代码:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button rollButton;
rollButton = findViewById(R.id.rollButton);
final ImageView leftDice = findViewById(R.id.diceLeft);
final ImageView rightDice = findViewById(R.id.diceRight);
final ImageView topDice = findViewById(R.id.diceTop);
final int [] diceArray = {
R.drawable.perspective_dice_one,
R.drawable.perspective_dice_two,
R.drawable.perspective_dice_three,
R.drawable.perspective_dice_four,
R.drawable.perspective_dice_five,
R.drawable.perspective_dice_six,
};
rollButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Dice", "You pressed the button!");
Random randomNumberGenerator = new Random();
int number = randomNumberGenerator.nextInt(6);
Log.d("Dice", "The random number is: " + number);
leftDice.setImageResource(diceArray[number]);
number = randomNumberGenerator.nextInt(6);
rightDice.setImageResource(diceArray[number]);
number = randomNumberGenerator.nextInt(6);
topDice.setImageResource(diceArray[number]);
}
});
}
}