繁体   English   中英

从Android应用程序的操作栏中选择菜单选项时,将数据从一个活动传递到另一个活动

[英]Passing data from one activity to another when choosing a menu option from action bar in Android app

我不知道是否有人可以提供一些指导。

我有一个主类,用户将在其中输入他们的姓名。 然后,我希望用户从操作/应用程序栏中的可用选项中选择游戏。 当他们选择游戏时,他们在主类中输入的名称将显示在游戏类中。 我希望这是有道理的?

我知道这涉及使用意图将数据从一个活动传递到另一个活动,但是我看到的每个教程都涉及在主类中设置一个按钮(因此使用诸如onclicklistener之类的东西),但是我不希望有一个按钮。 我想选择菜单选项来完成相同的工作,但是我找不到任何方法。

提前致谢。

编辑-尝试添加代码

主班:

public class GameCentral extends AppCompatActivity {


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game_central_layout);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.commonmenus, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.guessingGame) {

        startActivity(new Intent(this, Task3Activity.class));
        switch (item.getItemId()) {
            case R.id.playerNameEntered:
                startActivity(this, Task3Activity.class).putExtra(playerNameInput, value);

                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    else if (id ==R.id.placeOne) {

        Toast.makeText(this, "Game Placeholder One option is Clicked", Toast.LENGTH_SHORT).show();
    }
    else if (id ==R.id.placeTwo) {

        Toast.makeText(this, "Game Placeholder Two option is Clicked", Toast.LENGTH_SHORT).show();
    }
    else if (id ==R.id.placeThree) {

        Toast.makeText(this, "Game Placeholder Three option is Clicked", Toast.LENGTH_SHORT).show();
    }

    return super.onOptionsItemSelected(item);
}

}

游戏类

public class Task3Activity extends GameCentral {

public Button rtnBtn;
// button to return to Game Central at any point when clicked
public void init() {
    rtnBtn = (Button)findViewById(R.id.returnBtn);
    rtnBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent homeScreen = new Intent(Task3Activity.this, GameCentral.class);

            startActivity(homeScreen);
        }
    });
}

String value;

int attempts = 0;
final int maxAttempts = 1;
Random randGen = new Random();
int ranNum;
private SoundPlayer sound;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.task3_layout);
    init();

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        value = extras.getString("Value1");
        if (value  != null) {
            TextView dataRcvd = (TextView) findViewById(R.id.playerNameEntered);
            dataRcvd.setText(value );
        }
    }

    sound = new SoundPlayer(this);

    final TextView textResponse = (TextView) findViewById(R.id.txtResponse);
    final TextView guessText = (TextView) findViewById(R.id.txtAnswer);
    final EditText userGuess = (EditText) findViewById(R.id.etNumber);
    Button pressMe = (Button) findViewById(R.id.btnGuess);
    final Button rtnButton = (Button) findViewById(R.id.returnBtn);

    int min = 1;
    int max = 19;
    randGen = new Random();
    // Generate number once
    ranNum = randGen.nextInt(max - min + 1) + min;

    final Toast toast = Toast.makeText(getApplicationContext(), "Please guess between 0 and 20", Toast.LENGTH_LONG);
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 350);


    // When the button is clicked, it shows the text assigned to the txtResponse TextView box
    pressMe.setOnClickListener(new View.OnClickListener() {


                                   @Override
                                   public void onClick(View v) {
           boolean correct = false;
           final AlertDialog.Builder alert = new AlertDialog.Builder(Task3Activity.this);
           alert.setTitle("Unlucky");
           alert.setCancelable(false);
           alert.setMessage("You have guessed incorrectly three times. " +
                   "The answer was " + ranNum + ". " + "Would you like to play again?")
                   //.setCancelable(true)
                   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                           //dialog.dismiss();
                           Intent i = new Intent(Task3Activity.this, Task3Activity.class);
                           i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                           startActivity(i);


                       }
                   });

           alert
                   .setNegativeButton("No", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int i) {
                           //Task1Activity.this.finish();
                           dialog.dismiss();
                           //finishAffinity();
                           Intent toy = new Intent(Task3Activity.this, GameCentral.class);

                           startActivity(toy);
                       }

                       ;
                   });


           final AlertDialog.Builder alert2 = new AlertDialog.Builder(Task3Activity.this);
           alert2.setTitle("You Did It!");
           alert2.setCancelable(false);
           alert2.setMessage("The answer was " + ranNum + ". " + "Would you like to play again?")
                   //.setCancelable(true)
                   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                           //dialog.dismiss();
                           Intent i = new Intent(Task3Activity.this, Task3Activity.class);
                           i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                           startActivity(i);


                       }
                   });

           alert2
                   .setNegativeButton("No", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int i) {
                           //Task1Activity.this.finish();
                           dialog.dismiss();
                           Intent toy = new Intent(Task3Activity.this, GameCentral.class);

                           startActivity(toy);
                           //finishAffinity();
                       }

                       ;
                   });



           int userNumber = Integer.parseInt(userGuess.getText().toString());

           if ((userNumber < 1) || (userNumber > 19)) {
               //guessText.setText("Please guess between 0 and 20");
               //guessText.setBackgroundColor(Color.WHITE);
               toast.show();
           } else if (userNumber < ranNum) {
               guessText.setText("Your answer is too low. Guess again!");
               guessText.setBackgroundColor(Color.YELLOW);
               //sound.playBuzzerSound();
           } else if (userNumber > ranNum) {
               guessText.setText("Your answer is too high.  Guess again!");
               guessText.setBackgroundColor(Color.RED);
               //sound.playBuzzerSound();
           } else if (userNumber == ranNum) {
               ranNum = randGen.nextInt(20);
               //guessText.setText("You did it!");
               //guessText.setBackgroundColor(Color.WHITE);
               correct = true;
               alert2.show();
               sound.playApplauseSound();
           }

           if (attempts++ > maxAttempts && !correct) {
               alert.show();
               sound.playBooSound();
               //guessText.setText("You have guessed incorrectly three times.  The answer was " + ranNum);
           } else if (correct) {
           } else {
               String randText = "";


               randText = Integer.toString(ranNum);
               textResponse.setText("");

               userGuess.setText("");


           }

       }
   }
    );


}
}

因为您没有在意图中传递Bundle,所以不需要使用getIntent().getExtras();

游戏中心:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.guessingGame:
            Intent intent = new Intent(GameCentral.this, Task3Activity.class);
            intent.putExtra("PlayerName", "Name");

            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Task3Activity:

public class Task3Activity extends AppCompatActivity {

...

    @Override
    public void onCreate(Bundle savedInstanceSate) {
        ...

        String playerName = getIntent().getStringExtra("PlayerName");

        if (playerName != null) {
            TextView dataRcvd = (TextView) findViewById(R.id.playerNameEntered);
            dataRcvd.setText(playerName);
        }
    }

    ...
}

intent.putExtra("PlayerName", "Name"); 其中“名称”是从中获取播放器名称的字符串。 如果要从文本框中获取播放器的名称,则需要在“活动”范围内创建EditText对象。

if (id == R.id.guessingGame) {
        startActivity(new Intent(this, Task3Activity.class));
        switch (item.getItemId()) {
            case R.id.playerNameEntered:
                Bundle b = getIntent().getExtras();
                value= b.getString("playerNameInput");

                startActivity(this, Task3Activity.class).putExtra("playerNameInput", value);

                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

就我而言,我经常使用bundle在onOptionsItemSelected函数中获取字符串。
要激活此功能,应在每次更改活动时发送data(playerNameInput)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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