Continuous view of helloPe's android project practice-implementation (III)

Source: Internet
Author: User

The previous two "implementations" have basically implemented the background framework of the program. Today, the activity class of the program will be involved. In this class, in order to have a better visual effect, we will introduce some animation effects in android, which are implemented by animation, and briefly introduce the implementation of custom dialog in android; first, let's take a look at the running time of the game interface (the pictures in the program use the online users only for learning ):

The game runtime interface is used to display the custom dialog display of game results.

Let's take a look at the code in the activity class used to display the program (Here we mainly call and so on, and the Implementation logic is included in the previous two articles)

Package nate. llk; // The package must be imported with the public class GameActivity extends Activity implements listener, OnTimerListener, OnStateListener {private ImageButton img_startPlay; private ImageView img_title; private ProgressBar progress; private myalog dialog; alog; // visibility at first is "gone" private ImageView clock; private GameView gameView = null; private ImageButton img_tip; private ImageButton img_refresh; priva Te TextView text_refreshNum; private TextView text_tipNum; // effect of the two help buttons private Animation anim = null; private Handler handler = new Handler () {@ Overridepublic void handleMessage (Message msg) {switch (msg. what) {case 0: dialog = new MyDialog (GameActivity. this, gameView, "done! ", GameView. getTotalTime ()-progress. getProgress () + 1); dialog. show (); break; case 1: dialog = new MyDialog (GameActivity. this, gameView, "failed! ", GameView. getTotalTime ()-progress. getProgress () + 1); dialog. show () ;}};/** Called when the activity is first created. * // @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. game_view); anim = AnimationUtils. loadAnimation (this, R. anim. shake); findView (); startView (); img_startPlay.setOnClickListener (new BtnClickListener (); game View. setOnTimerListener (this); gameView. setOnStateChangeListener (this); gameView. setOnToolsChangedListener (this); img_refresh.setOnClickListener (new BtnClickListener (); img_tip.setOnClickListener (new BtnClickListener ();} // end of the OnCreate method! /*** Find the corresponding resource control */public void findView () {clock = (ImageView) this. findViewById (R. id. clock); progress = (ProgressBar) this. findViewById (R. id. timer); img_title = (ImageView) this. findViewById (R. id. title_img); img_startPlay = (ImageButton) this. findViewById (R. id. play_btn); img_tip = (ImageButton) this. findViewById (R. id. tip_btn); img_refresh = (ImageButton) this. findViewById (R. id. refresh_btn); gameView = (GameView) this. findViewById (R. id. game_view); text_refreshNum = (TextView) this. findViewById (R. id. text_refresh_num); text_tipNum = (TextView) this. findViewById (R. id. text_tip_num);}/*** program opening interface display */public void startView () {Animation scale = AnimationUtils. loadAnimation (this, R. anim. scale_anim); img_title.startAnimation (scale); img_startPlay.startAnimation (scale);}/*** displayed on the game runtime page, that is, the layout of the connected view */public v Oid playingView () {Animation scaleOut = AnimationUtils. loadAnimation (this, R. anim. scale_anim_out); img_title.startAnimation (scaleOut); img_startPlay.startAnimation (scaleOut); img_title.setVisibility (View. GONE); img_startPlay.setVisibility (View. GONE); clock. setVisibility (View. VISIBLE); progress. setMax (gameView. getTotalTime (); progress. setProgress (gameView. getTotalTime (); progress. setVisibility (Vi Ew. VISIBLE); gameView. setVisibility (View. VISIBLE); img_tip.setVisibility (View. VISIBLE); img_refresh.setVisibility (View. VISIBLE); text_tipNum.setVisibility (View. VISIBLE); text_refreshNum.setVisibility (View. VISIBLE); Animation animIn = AnimationUtils. loadAnimation (this, R. anim. trans_in); gameView. startAnimation (animIn); img_tip.startAnimation (animIn); img_refresh.startAnimation (animIn); text_tipNum. StartAnimation (animIn); text_refreshNum.startAnimation (animIn); // player. pause (); gameView. startPlay (); toast () ;}/ *** a process starts the game, refresh, class * @ author HelloPe | NatePan **/class BtnClickListener implements OnClickListener {@ Overridepublic void onClick (View v) {switch (v. getId () {case R. id. play_btn: playingView (); break; case R. id. refresh_btn: img_refresh.startAnimation (anim); gameView. refreshC Hange (); gameView. invalidate (); break; case R. id. tip_btn: img_tip.startAnimation (anim); gameView. autoHelp (); break ;}}@ Overridepublic void onRefreshChanged (int count) {text_refreshNum.setText ("" + gameView. getRefreshNum ();} @ Overridepublic void onTipChanged (int count) {text_tipNum.setText ("" + gameView. getTipNum ();} @ Overridepublic void onTimer (int leftTime) {progress. setProgress (leftTime);}/*** used to control the playing of music Put */@ Overridepublic void OnStateChanged (int StateMode) {switch (StateMode) {case GameView. WIN: handler. sendEmptyMessage (0); break; case GameView. LOSE: handler. sendEmptyMessage (1); break; case GameView. PAUSE: // player. stop (); // gameView. player. stop (); gameView. stopTimer (); break; case GameView. QUIT: // player. release (); // gameView. player. release (); gameView. stopTimer (); break;} public void quit () {this. finish (); }/*** Indicates the start time of the game. */public void toast () {Toast. makeText (this, "the game has started! Total time: "+ gameView. getTotalTime () + "s", Toast. LENGTH_LONG ). show () ;}@ Override protected void onPause () {super. onPause (); gameView. setMode (GameView. PAUSE) ;}@ Overrideprotected void onDestroy () {super. onDestroy (); gameView. setMode (GameView. QUIT) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {menu. add (Menu. NONE, 1, Menu. NONE, "Replay "). setIcon (R. drawable. buttons_replay); menu. add (Menu. NONE, 2, Menu. NONE, "Pause "). setIcon (R. drawable. pause); menu. add (Menu. NONE, 3, Menu. NONE, "SoundOn "). setIcon (R. drawable. volume); return super. onCreateOptionsMenu (menu) ;}@ Overridepublic boolean onOptionsItemSelected (MenuItem item) {switch (item. getItemId () {case 1: gameView. setTotalTime (100); progress. setMax (100); gameView. startPlay (); break; case 2: gameView. stopTimer (); if (item. getTitle (). equals ("Pause") {item. s EtTitle ("Continue"); item. setIcon (R. drawable. play);} else if (item. getTitle (). equals ("Continue") {item. setTitle ("Pause"); item. setIcon (R. drawable. pause);} AlertDialog. builder dialog = new AlertDialog. builder (this); dialog. setIcon (R. drawable. icon); dialog. setTitle ("continue"); dialog. setMessage ("continue the game? "); Dialog. setPositiveButton ("continue", new DialogInterface. onClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {gameView. setContinue ();}}). setNeutralButton ("replay", new DialogInterface. onClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {gameView. startPlay ();}}). setNegativeButton ("exit", new DialogInterface. onClickListener () {@ Overridepublic void OnClick (DialogInterface dialog, int which) {Intent startMain = new Intent (Intent. ACTION_MAIN); startMain. addCategory (Intent. CATEGORY_HOME); startMain. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK); startActivity (startMain); System. exit (0) ;}}); dialog. show (); break; case 3: // if (item. getTitle (). equals ("Mute") {item. setTitle ("SoundOn"); item. setIcon (R. drawable. volume);} else if (item. get Title (). equals ("SoundOn") {item. setTitle ("Mute"); item. setIcon (R. drawable. mute);} break;} return super. onOptionsItemSelected (item);}/*** listens to the backend button to prevent false clicking. After the back button is pressed, the program should be in the paused state */@ Overridepublic boolean onKeyDown (int keyCode, keyEvent) {if (keyCode = KeyEvent. KEYCODE_BACK) {AlertDialog. builder dialog = new AlertDialog. builder (GameActivity. this ). setTitle ("Quit game "). setMessage ("are you sure you want to quit the game? "). SetPositiveButton ("yes", new DialogInterface. onClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {Intent startMain = new Intent (Intent. ACTION_MAIN); startMain. addCategory (Intent. CATEGORY_HOME); startMain. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK); startActivity (startMain); System. exit (0 );}}). setNegativeButton ("no", new DialogInterface. onClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {Toast. makeText (GameActivity. this, "Restarting the game", Toast. LENGTH_LONG ). show (); gameView. startPlay () ;}}); dialog. setIcon (R. drawable. icon); dialog. show ();} return super. onKeyDown (keyCode, event );}}

In this class, as we said last time, we implemented the three previously defined interfaces and referenced the GameView class (used in the layout file of the activity ), use the following in the activity layout file:

  <nate.llk.view.GameView    android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:id="@+id/game_view"    android:visibility="gone"    android:layout_below="@id/timer"    />

Similarly, the custom dialog is the same as the custom GameView (inherited from the View. The MyDialog class inherits from the Dialog class and implements the OnClick method of OnClickListener. It uses a layout file to customize the dialog layout. The layout file is simple. The MyDialog class is as follows:

Package nate. llk; // skip the import package
public class MyDialog extends Dialog implements OnClickListener{private GameView gameview;private Context context;public MyDialog(Context context, GameView gameview, String msg, int time) {super(context,R.style.dialog);this.gameview = gameview;this.context = context;this.setContentView(R.layout.dialog_view);TextView text_msg = (TextView) findViewById(R.id.text_message);TextView text_time = (TextView) findViewById(R.id.text_time);ImageButton btn_menu = (ImageButton) findViewById(R.id.menu_imgbtn);ImageButton btn_next = (ImageButton) findViewById(R.id.next_imgbtn);ImageButton btn_replay = (ImageButton) findViewById(R.id.replay_imgbtn);text_msg.setText(msg);text_time.setText(text_time.getText().toString().replace("$", String.valueOf(time)));btn_menu.setOnClickListener(this);btn_next.setOnClickListener(this);btn_replay.setOnClickListener(this);this.setCancelable(false);}@Overridepublic void onClick(View v) {this.dismiss();switch(v.getId()){case R.id.menu_imgbtn:Dialog dialog = new AlertDialog.Builder(context)            .setIcon(R.drawable.buttons_bg20)            .setTitle(R.string.quit)            .setMessage(R.string.sure_quit)            .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {                public void onClick(DialogInterface dialog, int whichButton) {                ((GameActivity)context).quit();                }            })            .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {                public void onClick(DialogInterface dialog, int whichButton) {                gameview.startPlay();                }            })            .create();dialog.show();break;case R.id.replay_imgbtn:gameview.startPlay();break;case R.id.next_imgbtn:gameview.startNextPlay();break;}}@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {if(keyCode == KeyEvent.KEYCODE_BACK){this.dismiss();}return super.onKeyDown(keyCode, event);}}

The above code is simple, but it still achieves better results.

There are four types of animations for using animation in android. The use of Tween animation can also make the program look better:

In the anim file:

When two tool buttons in the program are clicked, the tool button is jittery:

<?xml version="1.0" encoding="utf-8"?><translate xmlns:android="http://schemas.android.com/apk/res/android" android:fromXDelta="0" android:toXDelta="10" android:duration="1000" android:interpolator="@anim/cycle" />
<? Xml version = "1.0" encoding = "UTF-8"?> <CycleInterpolator xmlns: android = "http://schemas.android.com/apk/res/android" android: cycles = "7"/> <! -- Used to control the number of vibrations above -->

The icon used to control the appearance of the welcome interface gradually becomes larger:

<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"><scale          android:interpolator="@android:anim/accelerate_decelerate_interpolator"          android:fromXScale="0.0"          android:toXScale="1.0"          android:fromYScale="0.0"          android:toYScale="1.0"          android:pivotX="50%"          android:pivotY="50%"          android:fillAfter="true"          android:duration="1600" /></set>

Of course, to enlarge the image, just change android: fromXScale = "1.0" and android: toXScale = "0.0;

As for the transparency effect, it is used to slowly display the content in the GameView from the transparency:

<?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"><alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="1000" /></set>

The usage of the above resources in the activity has been given in the above activity Class. Load the resource first, and then call the startAnimation method of imageView or other View;

The method for Playing Sound Effects in games is relatively simple. It is mainly complicated to play different sounds in different States. There are two methods for Playing Sound Effects in android: SoundPool, mediaPlayer. SoundPool is suitable for short promotion music, but the response speed requirement is relatively high; MediaPlayer is the opposite. The procedure is as follows:

// Initialize the soundPool object. The first parameter is the number of sound streams that can be played simultaneously. The second parameter is the sound type, and the third parameter is the sound quality soundPool = new SoundPool (25, audioManager. STREAM_MUSIC, 100); // reference soundPool for SoudPool. load (context, raw, 1); // call the load function to load music resources. // call the play function to play the corresponding music Resources in the parameters.

This program has been completed, and I have learned a lot from netizens. After all, it is a small project that many people have done. Record it. I hope you can pass by without spraying it ~

While (success! = Try ());

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.