2048点滴(一)

13 篇文章 0 订阅

最近在学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的生命周期图


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值