在恢复主要活动时更新TextView

时间:2012-06-03 11:13:05

标签: android android-intent textview android-activity onresume

以下提供的此代码中的朋友,我想在播放意图恢复时刷新我的文本视图。但每当我尝试从OnCreate中定义我的textview但在我的主类中(在静态int分数之后),我的应用程序崩溃。

public class MainProjectActivity extends Activity {
    /** Called when the activity is first created. */

    static int Score = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //Display Scores
        final TextView displayScores = (TextView)findViewById(R.id.scoreDisplay);
        displayScores.setText("Your Score : "+ Score);

        //Play Game button activity
        Button gameButton = (Button)findViewById(R.id.PlayButton);
        gameButton.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent play = new Intent(getApplicationContext(), com.sample.game.PlayScreen.class);
                startActivity(play);
            }
        });

3 个答案:

答案 0 :(得分:3)

我首先添加super.onResume();:

@Override
protected void onResume(){
    super.onResume();
    // The rest
}

我也会删除它:

final TextView displayScores = (TextView)findViewById(R.id.scoreDisplay);
        displayScores.setText("Your Score : "+ Score);
来自onCreate的

,并将其添加到onResume(),因为每次调用onCreate时,也会调用onResume。

也从public更改为protected onResume()

答案 1 :(得分:1)

试试这个:

public class MainProjectActivity extends Activity {
    /** Called when the activity is first created. */
TextView displayScores;
    static int Score = 0;
@Override
protected void onResume(){
    super.onResume();
    // code to update the date here
    displayScores.setText("Your Score : "+ Score);

}
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //Display Scores
        displayScores = (TextView)findViewById(R.id.scoreDisplay);
        displayScores.setText("Your Score : "+ Score);

        //Play Game button activity
        Button gameButton = (Button)findViewById(R.id.PlayButton);
        gameButton.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent play = new Intent(getApplicationContext(), com.sample.game.PlayScreen.class);
                startActivity(play);
            }
        });

答案 2 :(得分:0)

@Override
    protected void onResume() {
        // TODO Auto-generated method stub

        displayScores.setText("Your Score : "+ Score);

        super.onResume();
    }