And here’s the source code:
package com.pdg.android.sandbox; import java.util.Random; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class SandboxActivity extends Activity { private static final int INITIAL_GUESS_COUNT = 0; private static final int NUMBER_MAXIMUM = 100; private static final int NUMBER_MINIMUM = 1; private int guessCount; private Random random = new Random(); private int number; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); startGame(); } private void startGame() { pickNumber(); setGuessCount(INITIAL_GUESS_COUNT); setPrompt(getString(R.string.guess_my_number)); updateGuessStatus(); } private void pickNumber() { setNumber(random.nextInt(NUMBER_MAXIMUM-NUMBER_MINIMUM+1)+NUMBER_MINIMUM); } private void setNumber(int theNumber) { number = theNumber; } private int getNumber(){ return number; } private void updateGuessStatus() { setGuessStatus(String.format(getString(R.string.guess_count_format), getGuessCount())); } private void setGuessStatus(String theGuessStatus) { TextView tv = (TextView)findViewById(R.id.guessCount); tv.setText(theGuessStatus); } private int getGuessCount() { return guessCount; } private void setGuessCount(int theGuessCount) { guessCount = theGuessCount; } private void setPrompt(String thePrompt) { TextView tv = (TextView)findViewById(R.id.prompt); tv.setText(thePrompt); } public void guessButtonPressed(View view){ EditText et = (EditText)findViewById(R.id.currentGuess); int theGuess = Integer.parseInt(et.getText().toString()); setGuessCount(getGuessCount()+1); updateGuessStatus(); if(theGuessgetNumber()){ setPrompt(getString(R.string.guess_too_high)); }else{ setPrompt(getString(R.string.guess_correct)); setGuessCount(INITIAL_GUESS_COUNT); pickNumber(); } } }
Yes, it is the perennial classic “Guess My Number 1 to 100” game that just about everyone has written.
Why did I write this?
Mainly, I’m teaching myself the view based xml ui for android.
This is how I do it.
By writing an entirely too simplistic game.
But now I know how to put resources correctly into xml files, how to grab widgets by id, and how to set text values on TextViews.
Of course, the thing still blows up if you don’t put anything into the edit box and press “Guess!”, but that’s a feature!