由于代码比较简单,这里主要贴出代码,重要的部分有注释
1.文件结构
2.activity_main.xml布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background">
<!--图片按钮-->
<ImageButton
android:id="@+id/yy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
<!--保证背景透明-->
android:background="@android:color/transparent"
android:onClick="isPlayOrPause"
android:src="@drawable/yy"/>
</RelativeLayout>
3.MainActivity.java文件
package com.example.greetingcard;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void isPlayOrPause(View view){
ImageButton imageButton = (ImageButton)view;
//RotateAnimation animation = new RotateAnimation(0, 360);
//animation.setDuration(100000);
//animation.setRepeatCount(Animation.INFINITE);
//animation.setRepeatMode(Animation.RESTART);
if(mediaPlayer == null){
//imageButton.startAnimation(animation);
//获取应用内的音乐文件
mediaPlayer = MediaPlayer.create(this, R.raw.en);
mediaPlayer.start();
}
else if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
//imageButton.clearAnimation();
}
else{
mediaPlayer.start();
//imageButton.startAnimation(animation);
}
}
}
效果: