简体   繁体   中英

Passing an Intent

I have a simple game where you click a sprite which increments a hit counter. Once the game is over I want the score to be passed over the the main menu from where the game is started but can't get it to work. Here is my code for three different classes, I'm not sure what to put in the method.

Game Activity-

public void finish(){
          Intent returnIntent = new Intent();
          returnIntent.putExtra("GAME_SCORE",gameView.getHitCount());
          setResult(RESULT_OK, returnIntent);
          super.finish();
        }

Game View-

public String getHitCount() {

        String Score = Integer.toString(hitCount);
        return Score;

                /*Intent returnIntent = null;
                String Result = returnIntent.getExtras().getString("GAME_SCORE");
                TextView GameScore = (TextView)findViewById(R.id.tvGuessGame);
                GameScore.setText(Result);
                return Result;*/
        }

Main Menu-

protected void onActivityResult(int requestCode, int resultCode, Intent retIntent) {
        // Check which request we're responding to
        if (requestCode == SCORE_REQUEST_CODE) {
            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
                if (retIntent.hasExtra("GAME_SCORE")) {
                    int scoreFromGame = retIntent.getExtras().getInt("GAME_SCORE");
                    tvScore.setText(Integer.toString(scoreFromGame));
                }
            }   
        }

    }

游戏得分为字符串,但在onActivityResult中以int形式获取

  1. Change your return type of getHitCount() method.

    public int getHitCount(){

      return hitCount; } 
  2. In onActivityResult :

    tvScore.setText(""+Integer.toString(scoreFromGame));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM