最近在学android,昨天过了一遍think in java 4,做了一些摘要笔记。今天开始正式学习android,之前其实也有学过一段时间,断断续续的,但现在真的决意要好好学了。
这份源代码是我用于阅读学习只用(网上有很多,各种版本)。大家可去下载一份来玩。我只是记录下个人的点滴感悟,并非有什么传道受业的想法。因此权当给自己备忘,写的不甚仔细。
public class MainActivity extends Activity {
public MainActivity() {
mainActivity = this;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
root = (LinearLayout) findViewById(R.id.container);
root.setBackgroundColor(0xfffaf8ef);
tvScore = (TextView) findViewById(R.id.tvScore);
tvBestScore = (TextView) findViewById(R.id.tvBestScore);
gameView = (GameView) findViewById(R.id.gameView);
btnNewGame = (Button) findViewById(R.id.btnNewGame);
btnNewGame.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) {
gameView.startGame();
}});
animLayer = (AnimLayer) findViewById(R.id.animLayer);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void clearScore(){
score = 0;
showScore();
}
public void showScore(){
tvScore.setText(score+"");
}
public void addScore(int s){
score+=s;
showScore();
int maxScore = Math.max(score, getBestScore());
saveBestScore(maxScore);
showBestScore(maxScore);
}
public void saveBestScore(int s){
Editor e = getPreferences(MODE_PRIVATE).edit();
e.putInt(SP_KEY_BEST_SCORE, s);
e.commit();
}
public int getBestScore(){
return getPreferences(MODE_PRIVATE).getInt(SP_KEY_BEST_SCORE, 0);
}
public void showBestScore(int s){
tvBestScore.setText(s+"");
}
public AnimLayer getAnimLayer() {
return animLayer;
}
private int score = 0;
private TextView tvScore,tvBestScore;
private LinearLayout root = null;
private Button btnNewGame;
private GameView gameView;
private AnimLayer animLayer = null;
private static MainActivity mainActivity = null;
public static MainActivity getMainActivity() {
return mainActivity;
}
public static final String SP_KEY_BEST_SCORE = "bestScore";
}
初学者一般会疑惑,为什么mainActivity在后定义,前面使用了呢?
经查阅资料,static 类型在类型被加载的时候就已经初始化好了的;也就是说mainActivity在对象构造之前就已经存在了的。因此可以在前面开头就引用,毫无问题。这点在tij4中也有很好的说明(java的基础还是必要的)。
最后附上Activity的生命周期图