切换活动后,方法停止运行

时间:2017-07-23 03:28:54

标签: android

在这个应用程序中,用户得分应该每隔一秒左右增加,他们可以使用该分数并从第二个活动中购买升级。当用户启动应用程序时,程序运行正常,但当它们从第一个活动转到第二个活动并返回时,它会停止更新textview,其得分每秒都会增加。你们能解释一下发生了什么吗?

package com.example.navjeevenmann.mytycoon;

import android.content.Intent;
import android.os.Bundle;    
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
private Button myButton;
private int Counter;
private Button myButton2;
private TextView myTextView;
Handler handler = new Handler();
private int add = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);
    super.onCreate(savedInstanceState);
    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        if (bundle.containsKey("Count")) {
            Counter = bundle.getInt("Count");
        }
        if (bundle.containsKey("Add")) {
            add = bundle.getInt("Add");
        }
    }


    myButton = (Button) findViewById(R.id.button);
    myButton2 = (Button) findViewById(R.id.button2);
    myTextView = (TextView) findViewById(R.id.textView);

    myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Counter = ButtonCounter(Counter);
        }
    });
    myButton2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), 
SecondActivity.class);
            intent.putExtra("Count", Counter);
            startActivity(intent);
        }

    });
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Counter= AutoCounter(Counter, add);
            Display(Counter);
            handler.postDelayed(this, 1000);
        }
    },100);
}


public int ButtonCounter(int Counter) {
    Counter += 1;
    return Counter;
}

public int AutoCounter(int Counter, int add) {
    Counter += add;
    return Counter;
}

public void Display(int Counter) {
    String man = String.valueOf(Counter);
    myTextView.setText("$" + man);

}

 }

1 个答案:

答案 0 :(得分:0)

只在onCreate()方法内启动计数处理程序。 当您从SecondActivity返回到MainActivity时,会调用onResume()方法,所以 您需要在onResume()方法内开始计数。

P.S 在从postDelay()更新用户界面之前,请务必检查空值。

您的活动可能会在代码运行时被销毁,请确保您的TextView在更新前不为空。