How to pass a random number from one class to another class?
I'm making Sudoku game. There are two classes: difficulty and Screen class. When the 'easy' button is pressed, I want to generate a random number from 1 to 9, and that numbers should go to the Screen class layout.
My 'easy' button is in choos开发者_开发知识库edifficulty
class layout.
You can pass information between activities using Intent extras. In your case, you could do (assuming I understood what you wanna do):
public void startSudoku(int chosenDifficulty) {
Intent i = new Intent(this, // Your current activity
SudokuActivity.class); // The activity showing the Sudoku
i.addExtra("com.example.sudoku.DifficultyLevel", chosenDifficulty);
startActivity(i);
}
Then, in the onCreate method of your Sudoku activity, you can get the difficulty level:
private int difficulty = 0;
protected void onCreate(Bundle savedInstanceState) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
difficulty = extras.getInt("com.example.sudoku.DifficultyLevel", 0);
}
}
Be carefull cause a sudoku is not only "random numbers from 1 to 9", so I recommend you to implement the algorithm properly. (Take a look at http://en.wikipedia.org/wiki/Sudoku_algorithms).
About passing data from one activity to another, you can use the intent. For example:
//In the place you launch your game
Intent myIntent = new Intent(myContext, Screen.class);
//sudoku is a String, for example, that contains the sudoku you want to pass
myIntent.putExtra("sudokukey", sudoku);
startActivity(myIntent);
And then, to retrieve the data:
Bundle bundle = getIntent().getExtras();
String mySudoku = bundle.getString("sudokukey");
精彩评论