1. 程式人生 > >Android-五子連珠(四)-MainActivity的Java程式碼

Android-五子連珠(四)-MainActivity的Java程式碼

package com.example.administrator.wuziqi;


import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends
AppCompatActivity {
private boolean music=true; ImageButton ismusic; MediaPlayer mediaPlayer1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //播放背景音樂 mediaPlayer1 = null
; mediaPlayer1 = MediaPlayer.create(this, R.raw.a2); mediaPlayer1.start(); //設定迴圈播放 mediaPlayer1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mediaPlayer1.start(); mediaPlayer1.setLooping(true
); } }); //用聲音小圖示來暫停和播放音樂 ismusic=(ImageButton) findViewById(R.id.music); ismusic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(music) { mediaPlayer1.pause(); ismusic.setBackgroundResource(R.drawable.music1); music=false; } else { mediaPlayer1.start(); ismusic.setBackgroundResource(R.drawable.music); music=true; } } }); //利用button圖示來觸發悔棋和重新開局函式 final wuziqipan jj=(wuziqipan) findViewById(R.id.wuziqipan); ImageButton button=(ImageButton) findViewById(R.id.Huiqi); ImageButton button1=(ImageButton) findViewById(R.id.Replay); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { jj.Huiqi(); } }); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { jj.GameAgain(); } }); } //實現再按一次退出程式 private long exitTime = 0; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){ if((System.currentTimeMillis()-exitTime) > 2000){ Toast.makeText(getApplicationContext(), "再按一次退出程式", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { finish(); System.exit(0); } return true; } return super.onKeyDown(keyCode, event); } }