项目预览
开发环境
操作系统:Windows11 家庭版
开发工具:Android Studio 2023.1.1 Patch 2
jdk版本:jdk1.8
Android SDK版本:33
Gradle 版本:gradle-7.5
功能分析
界面上有一个风扇图片(使用ImageView展示),有四个控制按钮(使用Button组件),四个按钮分别为关闭风扇,一档速度,二档速度和三档速度。
给风扇图片添加一个旋转动画,
给四个按钮设置用户点击事件,根据用户点击设置风扇图片的转速和停止。
功能实现
风扇图片和动画初始化
风扇动画使用ObjectAnimator类实现。(ObjectAnimator类可以生实现很多类型的动画)
private ImageView fanImg; // 风扇图片
private ObjectAnimator rotationAnimator // 风扇动画
private void initObject(){
// 初始化风扇图片
fanImg = findViewById(R.id.fanImg);
// 初始化风扇动画
rotationAnimator = ObjectAnimator.ofFloat(fanImg, "rotation", 0f, 360f);
rotationAnimator.setDuration(1000); // 动画持续时间(毫秒)
rotationAnimator.setInterpolator(new LinearInterpolator());
rotationAnimator.setRepeatCount(ObjectAnimator.INFINITE); // 无限重复
rotationAnimator.setRepeatMode(ObjectAnimator.RESTART); // 重新开始
}
按钮初始化
把四个按钮使用一个Button数组
private final Button[] buttons = new Button[4];
private void initView(){
buttons[0] = findViewById(R.id.btnOff);
buttons[1] = findViewById(R.id.btn1);
buttons[2] = findViewById(R.id.btn2);
buttons[3] = findViewById(R.id.btn3);
}
按钮点击处理
用户点击按钮时先把按钮的背景色都初始化,然后根据点击的按钮设置背景色并设置风扇的转速。
private void setFan(int f){
// 按钮样式设置
for (Button button : buttons) {
button.setBackground(getDrawable(R.drawable.btn_off));
button.setTextColor(getResources().getColor(R.color.off));
}
buttons[f].setBackground(getDrawable(R.drawable.btn_on));
buttons[f].setTextColor(getResources().getColor(R.color.on));
// 风扇转速设置
switch (f){
case 0:
if (rotationAnimator.isStarted()) {
rotationAnimator.cancel();
}
break;
case 1:
if (!rotationAnimator.isStarted()) rotationAnimator.start();
rotationAnimator.setDuration(1600);
break;
case 2:
if (!rotationAnimator.isStarted()) rotationAnimator.start();
rotationAnimator.setDuration(1000);
break;
case 3:
if (!rotationAnimator.isStarted()) rotationAnimator.start();
rotationAnimator.setDuration(400);
break;
}
}
绑定用户点击
在setFan(int f)函数里已经实现了风扇转速的控制和停止,现在根据按钮功能绑定对应的操作就可以。
private void click(){
buttons[0].setOnClickListener(view -> setFan(0));
buttons[1].setOnClickListener(view -> setFan(1));
buttons[2].setOnClickListener(view -> setFan(2));
buttons[3].setOnClickListener(view -> setFan(3));
}
源代码
关注公众号《木木与代码》回复关键词“电风扇”